Thread: Simple Math

  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    8

    Simple Math

    This code worked perfectly at school in the lab but when I copied it to notepad and sent it to myself via email and pasted the code into Dec-C++ it no longer worked. When I run the program it should allow me to type a number such as four and give me an answer (in this case six). Instead of working and giving me the correct answer when i type in the number and press enter the command prompt window closes. I tried to fix it last night but I am not sure what could be wrong.

    Code:
    #include <stdio.h>
    int sum(int n)
    {
    if(n==0)
        return(0);
        else 
        return(sum(n-2)+n);
    }
    main()
     
     {
              int N;
              scanf("%d",&N);
              printf("The sum is %d.\n", sum(N));
              }

  2. #2
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    I think the better question is what reason would the command prompt have to stay open?

    The execution of the program has ended, the main method has returned.

    It did everything it was supposed to do, it simply closed the command prompt afterwards automatically, the same way it opened the command prompt automatically to begin execution of the program.

    You can stick a "gets()" at the end and it'll wait for a keypress.

    Or you can open the command prompt manually by hitting start >> run, typing "cmd" >> hitting enter.

    Going to your project directory where the compiled binaries are, and running the program via it's name.

    ie.
    If the program's name is "a.exe" - just typing "a.exe" in the command window will execute it. Windows knows (or thinks it knows) what to do with executables with extensions in its native executable format (.exe).

    When the program is finished running, the command prompt shall not close now.
    Last edited by Syndacate; 08-31-2010 at 09:25 AM.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    remove the "sum" in the return statement of function sum.

    If N==1, then all is well, otherwise, the N will never be 0, and continue to recursively call sum(). I use getchar() at the end of my programs, to hold open the console window:

    Typical last three lines of my programs are:
    Code:
      printf("\n\n\t\t\t    press enter when ready");
      getchar();
      return 0;
    BTW, int main() is standard C, and int main() needs a return 0, as well.
    Last edited by Adak; 08-31-2010 at 09:29 AM.

  4. #4
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    Quote Originally Posted by Adak View Post
    remove the "sum" in the return statement of function sum.

    If N==1, then all is well, otherwise, the N will never be 0, and continue to recursively call sum().
    Yeah, I think it will only work with even inputs. Though I hate recursion.

    It's definitely ending, which is why his command prompt is going away, so it's not stuck in an infinite recursive loop with no base case being met.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Syndacate View Post
    I think the better question is what reason would the command prompt have to stay open?

    The execution of the program has ended, the main method has returned.

    It did everything it was supposed to do, it simply closed the command prompt afterwards automatically, the same way it opened the command prompt automatically to begin execution of the program.

    You can stick a "gets()" at the end and it'll wait for a keypress.

    Or you can open the command prompt manually by hitting start >> run, typing "cmd" >> hitting enter.

    Going to your project directory where the compiled binaries are, and running the program via it's name.

    ie.
    If the program's name is "a.exe" - just typing "a.exe" in the command window will execute it. Windows knows (or thinks it knows) what to do with executables with extensions in its native executable format (.exe).

    When the program is finished running, the command prompt shall not close now.
    Don't ever use gets.

    The indentation could use some work, too, and main should have a return type of 0.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by Syndacate View Post
    Yeah, I think it will only work with even inputs. Though I hate recursion.

    It's definitely ending, which is why his command prompt is going away, so it's not stuck in an infinite recursive loop with no base case being met.
    If n equals 1:

    n-2+n will equal 0, and the function will return on the next recursive call it makes to sum()

    If n equals 2 or more:

    n-2+n will equal 2 or more, and the function will continue recursive calls to sum().

    Yes?

  7. #7
    Registered User
    Join Date
    Aug 2010
    Posts
    8
    Thanks! it works!!! Always fast responses! If only there was a rep system here so i could +rep everyone helping me. This is a great community.

  8. #8
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    Quote Originally Posted by Elysia View Post
    Don't ever use gets.

    The indentation could use some work, too, and main should have a return type of 0.
    I wouldn't, in practice, but this is for some school project, I doubt his professor will buffer overflow his submitted program to execute malicious code on his own computer *confused." For what he's using it for I would say it's fine, simple enough and straight enough to the point if he's still learning.

    Quote Originally Posted by Adak View Post
    If n equals 1:

    n-2+n will equal 0, and the function will return on the next recursive call it makes to sum()

    If n equals 2 or more:

    n-2+n will equal 2 or more, and the function will continue recursive calls to sum().

    Yes?
    I don't know, I suck at recursion - I don't use it.

    I would think:

    Passing it 2, initially:
    sum(n-2) where n = 2 would be sum(0) (return 0) + 2 would output 2.
    sum(n-2) where n = 3 would be sum(1)+3 >> sum(-1)+1 >> sum(-3)+-1 and it goes forever in a downward recursive spiral - I can see that.
    But for 4:
    sum(n-2) where n = 4 would be sum(2) >> sum(0) (return 0) + 2 >> 6.

    I see valid answers for 0, 2, 4..one would say via induction that that's enough to prove that it works for all even numbers. Though as I said, I really do suck at recursion, I don't use it, so I could obviously be very wrong. An explanation would be much appreciated, though.

  9. #9
    Registered User
    Join Date
    Jul 2010
    Location
    Oklahoma
    Posts
    107
    Amphibian,

    I assume that you brought it home to a Microsoft Windows computer. If that is indeed the case, then this line will produce the "Press any key to continue . . ." prompt:

    Code:
    system("pause");
    The 'pause' command is a component of the DOS shell (batch programming) facilities. I think it's been around since...version 4, and according to Van Wolverton Running MS-DOS 6th Ed. Washington: Microsoft Press 1993 ISBN 1-55615-542-5, prior to that version would produce the message: "Strike a key when ready...." The newer versions of Windows (DOS) are using something called 'PowerShell' now, and I think the implementation uses PERL for the batch processing language (?).

    The 'system()' function call, according to Paul S. Wang An Introduction to ANSI C on UNIX Boston: PWS Publishing 1993 ISBN 0-534-14232-X, is used to "[allow] execution of shell-level commands from within C programs...." He gives examples like copying files and the like. The inclusion of 'stdio.h' seems to make the library function available, but I suppose that depends on the compiler. I would confidently expect to find it in 'stdlib.h.'

    Best Regards,

    New Ink -- Henry
    Last edited by new_ink2001; 08-31-2010 at 10:20 AM. Reason: quotation mark around keyword

  10. #10
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Quote Originally Posted by Syndacate View Post
    I don't know, I suck at recursion - I don't use it.

    I would think:

    Passing it 2, initially:
    sum(n-2) where n = 2 would be sum(0) (return 0) + 2 would output 2.
    sum(n-2) where n = 3 would be sum(1)+3 >> sum(-1)+1 >> sum(-3)+-1 and it goes forever in a downward recursive spiral - I can see that.
    But for 4:
    sum(n-2) where n = 4 would be sum(2) >> sum(0) (return 0) + 2 >> 6.

    I see valid answers for 0, 2, 4..one would say via induction that that's enough to prove that it works for all even numbers. Though as I said, I really do suck at recursion, I don't use it, so I could obviously be very wrong. An explanation would be much appreciated, though.
    This is correct. Non-negative even numbers terminate; all other numbers are handled poorly.
    Quote Originally Posted by Syndacate View Post
    I wouldn't, in practice, but this is for some school project, I doubt his professor will buffer overflow his submitted program to execute malicious code on his own computer *confused." For what he's using it for I would say it's fine, simple enough and straight enough to the point if he's still learning.
    The point is that if he's still learning, he should learn the 'right' way to do it. gets() is almost never the 'right' way.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  11. #11
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    Quote Originally Posted by new_ink2001 View Post
    Amphibian,

    I assume that you brought it home to a Microsoft Windows computer. If that is indeed the case, then this line will produce the "Press any key to continue . . ." prompt:

    Code:
    system("pause");
    The 'pause' command is a component of the DOS shell (batch programming) facilities. I think it's been around since...version 4, and according to Van Wolverton Running MS-DOS 6th Ed. Washington: Microsoft Press 1993 ISBN 1-55615-542-5, prior to that version would produce the message: "Strike a key when ready...." The newer versions of Windows (DOS) are using something called 'PowerShell' now, and I think the implementation uses PERL for the batch processing language (?).

    The 'system()' function call, according to Paul S. Wang An Introduction to ANSI C on UNIX Boston: PWS Publishing 1993 ISBN 0-534-14232-X, is used to "[allow] execution of shell-level commands from within C programs...." He gives examples like copying files and the like. The inclusion of 'stdio.h' seems to make the library function available, but I suppose that depends on the compiler. I would confidently expect to find it in 'stdlib.h.'

    Best Regards,

    New Ink -- Henry
    Good info. I'm ........ed at myself for not knowing that, I use "pause" all the time in batch scripts, and I use system() from time to time in UNIX based systems, typically to call scripts or what-have you. Can't believe I didn't put 2 & 2 together. A lot more eloquent than through a random "read" in there such as gets();.

    Quote Originally Posted by pianorain View Post
    This is correct. Non-negative even numbers terminate; all other numbers are handled poorly.The point is that if he's still learning, he should learn the 'right' way to do it. gets() is almost never the 'right' way.
    Oh, ok, at least I get the simple recursive ones right sometimes :-P.

    Fair enough, I guess the way I see it is it's simply a factor of his environment. It wouldn't be an issue if he manually opened a command prompt, and if this was a real algorithm for a system's back-end or for a GUI application it wouldn't matter anyway. So I guess the way I see it is it's simply a matter of his way of execution, which wouldn't be practiced in the real world, y'know? But I do understand where you're coming from.

  12. #12
    Registered User
    Join Date
    May 2010
    Posts
    74
    you could try code::blocks (an IDE), it keeps the console window open, no need for extra code.

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Syndacate View Post
    Fair enough, I guess the way I see it is it's simply a factor of his environment. It wouldn't be an issue if he manually opened a command prompt, and if this was a real algorithm for a system's back-end or for a GUI application it wouldn't matter anyway. So I guess the way I see it is it's simply a matter of his way of execution, which wouldn't be practiced in the real world, y'know? But I do understand where you're coming from.
    The thing is: there is a difference between a simplified model and a dangerous model.
    Some things are fine to use if you're a newbie--like not handling input correctly. But some things are just outright dangerous, regardless if you're used in a controlled environment or not. gets is one of those.
    This leads to the topic of buffer overruns, which is a very real problem that plagues C today. Learning how to handle it is critical, regardless of where, how or why you're programming. Therefore using gets is always bad.
    Then there's the fact that gets will most likely be removed in the next C standard! The simple fact is that there's an easy and safe alternative: fgets. There is nothing fgets cannot do that gets can.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    Quote Originally Posted by Elysia View Post
    The thing is: there is a difference between a simplified model and a dangerous model.
    Some things are fine to use if you're a newbie--like not handling input correctly. But some things are just outright dangerous, regardless if you're used in a controlled environment or not. gets is one of those.
    This leads to the topic of buffer overruns, which is a very real problem that plagues C today. Learning how to handle it is critical, regardless of where, how or why you're programming. Therefore using gets is always bad.
    Then there's the fact that gets will most likely be removed in the next C standard! The simple fact is that there's an easy and safe alternative: fgets. There is nothing fgets cannot do that gets can.
    I realize the rationale behind it though I still disagree, especially about the "critical" aspect.

    While it's true, buffer overruns are a very feasible exploit, for a new programmer using it in a controlled env (an OS), using it as a standard user, I still don't see any issues. Sure, I would never advocate using it, but I wouldn't say it's as critical as you believe. What's the real danger, if somebody roots his computer they can execute a trojan they dropped in automagically? Sure, but I'd consider the trojan drop off and the rooting of the system larger problems to begin with. As for it accessing sys resources in a very negative way. In many mainstreamed OS's, Windows especially, most of that stuff is protected. There's no way a buffer overrun from an app level program could slip into HDD driver code and start eating data or anything malicious like that.

    I guess I fail to see that in beginning programming (ie. an echo program or some recursive proof of concept program) the harm that can be done by executing it in user-land under a non-root user. Sure, it can overflow and .. probably get seg faulted, but the largest issue I see with that is the size of the core dump stack trace it will leave, y'kno? Maybe an example (real world, beginning programming, app level, non-root, protective OS) can change my outlook on it.

    Again, I don't advocate the use of gets() - not by a landslide - but if some beginner chooses to use it in their programs which add two values together from stdin and print the results I don't see the critical aspects to it.

    I'd be really surprised if they removed it from the standard, despite its exploits and other possible issues, that's a big shot to backwards compatibility.

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Oh, so you like little nasty keyloggers that exploit buffer overruns, then? You don't need administrator privileges for that. Then there are a range of buffer run exploits and otherwise to get yourself "elevated," especially in Windows. And once you're elevated, the fun begins.

    Then consider yourself surprised.
    Quote Originally Posted by Wikipedia
    # The gets function, deprecated in the current C language standard revision, ISO/IEC 9899:1999/Cor.3:2007(E), is replaced by new safe alternative, gets_s.
    Source: C1X - Wikipedia, the free encyclopedia
    They already broke backward compatibility with C99. Why not C1X?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. trying to do simple math with float and int type
    By demuro1 in forum C Programming
    Replies: 16
    Last Post: 09-24-2008, 11:58 AM
  2. Getting bizarre results from simple math
    By mmyers1 in forum C++ Programming
    Replies: 3
    Last Post: 04-20-2004, 06:39 PM
  3. simple math in msvc++ 6
    By isnan in forum Windows Programming
    Replies: 2
    Last Post: 03-24-2004, 09:28 PM
  4. Simple Math Program
    By RazielX in forum C Programming
    Replies: 3
    Last Post: 03-04-2004, 06:22 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM