1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Triangle-Number Function. (C++)

Discussion in 'Scripting & Programming' started by aelonski, Mar 22, 2007.

  1. aelonski

    aelonski New Member

    7
    1
    9
    I'm very new to programming and am in a bit of a pickle with this.

    My triangle function is supposed to total all the whole numbers from 1 to the number specified, like this;

    triangle(5) = 1 + 2 + 3 + 4 + 5 = 15

    And then output the number 15.

    Here my code;

    Code:
    #include <iostream>
    using namespace std;
    
    int main() {
        int n;
        cout << "Enter a number and press ENTER. ";
        cin >> n;
        cout << "Function returned " << triangle(n);
        return 0;
    }
    
    int triangle(int n) {
        int i;
        int sum = 0;
        for (i = i; i <= n; i++)
        sum = sum + i;
        return sum;
    }
    When I run it and enter, for example the integer, 4. I get;

    Function returned -1498971578

    Or if I enter, for example the integer, 10. I get;

    Function returned -1498971533

    I'm sure I have done something stupid, but the number being returned don't make any sense to me at all.

    Thank you for reading my post.
     
    WIP: A+
  2. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    You've initialised int i with what is currently contained at that memory location (for(i = i...), which is garbage, instead of initialising it with zero.

    hth
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  3. aelonski

    aelonski New Member

    7
    1
    9
    Ah, I can't believe I didn't notice that. I must have checked through it 10 times. :blink

    I've initialized it with 1. All is working. Thanks.
     
    WIP: A+
  4. Bluerinse
    Honorary Member

    Bluerinse Exabyte Poster

    8,871
    167
    256
    Rep given where it's deserved 8)
     
    Certifications: C&G Electronics - MCSA (W2K) MCSE (W2K)
  5. Tom3

    Tom3 New Member

    9
    1
    26
    Hi.
    The nth triangular number is given by:

    1/2 n ( n + 1 )

    so you don't need looped code- just pop in the formula.

    Regards, Tom3

    PS don't forget to use float instead of int because of the 1/2 !!
     
    Certifications: none
    WIP: deciding
  6. aelonski

    aelonski New Member

    7
    1
    9
    Thank you again.

    I wasn't aware of the reping system, +rep! :biggrin
     
    WIP: A+
  7. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Cheers mate. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  8. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Yes, I knew that you should have initialised it to 1. Didn't want you to feel that I guided you all the way. Well done!

    As your experience grows with the language you'll spot such bugs immediately. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  9. aelonski

    aelonski New Member

    7
    1
    9
    Hehe, slowly but surly. C++ is the first programming language I've really thrown myself at, I tryed some assembler ages ago, (Z80) but it wasn't sticking. I was advised to learn C#, Visual Basic .NET or Java rather than C++ from a friend. I'm not looking at Games design, like what I read in your profile, mathematix, but would like to get into Application Design of some form. Still young, but my thoughts on the matter are that learning C++ can't be doing me any harm, and must help when it comes to learning different languages.
     
    WIP: A+
  10. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    I'm inclined to agree with your friends regarding the first language that you should approach. To be honest, I have encountered two people so far who have attempted C++ as there first language, and there have been two outcomes:

    1. They have good familiarity with the OOP principles presented by C++, but have no familiarity with procedural programming.
    2. I'm sure that you've read such phrases as C being a subset of C++ (which is not entirely true, btw). C is a procedural language and C++ is an OO language. Now, they produce code that any good C compiler would compile cleanly thinking that they are coding in C++! This is again because of a lack of an understanding of procedural programming.

    Now, just using C++ in itself does not mean that you're using the power of the language, it just means that you're using a small part of that 'power' and the effort invested could have been better spent with a less obfuscating language that deals with a lot of issues under the hood. The bug that you started this thread with might have been flagged in another language, but as it's C++ it leaves it to you to find such issues simply because its functionality is so low-level.

    I admire your enthusiasm for learning C++ as a first language, but would advise against it for the reasons given above. I would only advise that you start to learn C++ when:

    1. You understand procedural programming.

    Reason: OOP is not really understandable until you can contrast it with your understanding of procedural programming. Any good beginners programming course should give a solid overview of procedural languages prior to introducing C++.

    2. Effective use of C++ requires intricate understanding of algorithm efficiency.

    Reason: In the post above Tom3 gave a formula for calculating triangle numbers. Now, for small numbers that would be a more expensive calculation than iterating through a loop. For large numbers the formula would be better. Also the format of the calculation as presented is not the most efficient method

    (n ( n + 1 )) / 2 is more efficient than 1/2 n ( n + 1 ). Assuming n is an int I am calculating all integer arithmetic first (which is faster than floating-point arithmetic), then cast this integer value to float when I divide it by float(2). Tom3's way requires four-odd casts. Expensive! The precise number of casts is compiler dependent, hence the '-odd' approximation. ;)

    3. Given that C/C++ are such low-level languages, a thorough understanding of hardware at a very low level (at about the assembly level) is critical to squeezing every little bit of efficiency out of your code.

    Reason: Particularly for games bottlenecks always turn up! This can show in graphics and audio performance - or in the worst cases - the entire game can be one big bottleneck causing extremely sluggish performance. This requires profiling and refactoring to iron out the issues. This doesn't only happen for games. Also, the dreaded pointers that require the programmer to implement manual memory management. It is a nightmare unless properly understood. The list goes on...

    As you've said, you're young and are already a better programmer than I was when I was your age. Take your time and get the best that you can for the time that you are taking to learn.

    Good luck. :biggrin
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  11. aelonski

    aelonski New Member

    7
    1
    9
    Thank you so much for that comprehensive reply!

    I have very limited knowledge in the 'core' if you like, of programming, the 'fundamentals'. So at the moment, my initial comparisons between OO, and PP, are very limited! Resources are plentiful on the two, so it's only a matter of time before I am familiarized with the differences.

    With my limited knowledge, I have concluded that OO isn't overly useful in application development, I am most probably wrong, but like I mentioned earlier, I guess knowing, only adds another sting to one's bow. Whereas PP would be better suited to a newbie looking at Application development, right?

    If so, I have another question for you!

    So, learning C# would hone my skills toward PP, thus a better understanding when it comes to application development.

    And the Visual Studio .NET is based around C#? So it's all gravy, or is the VS .NET area a completely different kettle of fish? I do see the two "Job titles" separated when I look through various job advertisements.

    Java, I see HUNDREDS of advertisements wanting to recruit, 'JREE, blah' developers! I had always thought of Java as being more of a web applet program, than an actual application development language. How would Java stack up with C# when it comes down to careers in the application development field? And what would you suggest would be a better starting point between the two? I respect your opinion, and am grateful for the time your spending helping me out! :D
     
    WIP: A+
  12. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Honestly, don't mention it. :)

    When reading up on material prefer books over online resources. Books are invariably written by talented and experienced people. Web content regarding programming is often unverified and incomplete. You can pick out the good bit from the web with experience.

    Yes, you are very wrong about OO not being overly useful for application development. When writing large applications you will want to marry it because of the abstraction mechanisms it offers.

    OO is very valuable!

    At this stage you know of the existence of OO which is different from knowing OO. You'll get there in the end, though.

    Well, not really. Applications are written in a variety of languages, so you'll have to be familiar with all aspects if you want to be a flexible developer.

    Well, C# is an OO language. Again you won't be using it to its full potential, but it does offer you an easier ride whilst learning than C++ would. C++ will give you loads of frustrating errors along the way as your code base grows whilst learning.

    It's comprised of C#, C++, J++ and VB IDEs. Is that what you mean?

    C# is Microsoft's baby for offering a better alternative to C++ and the problems it comes with.

    Visual Studio is Microsoft's offering of an integrated development environment offering a complete solution to a variety of software development tasks. The binaries it generates is better suited to the Windows platform than any other out there. At least that's something along the lines of what they say.

    Apart from the specifics of its modifications to the C99 standard, that's about it.


    Unfortunately, there's no magic formula here. When looking for jobs you should be looking for the field of development over the language used. Whilst you are learning you will find yourself gravitating towards a field of development, for example mine is games yours is application development. It really depends on where you are most creative as a developer.

    For now just choose a language that you are comfy with. Your friend that has the good advice given to you? Work with him/her and draw from their experiences, learning from the mistakes that they've already made. Even if you're both at roughly the same level, still work together.

    Programming, as everything else, gets easier with time. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  13. aelonski

    aelonski New Member

    7
    1
    9
    A final thank you for all your help.

    I'm getting to work! :biggrin

    Thanks.
     
    WIP: A+
  14. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    No problem, mate. Enjoy!

    Haven't coded all day myself and i have a lot to do. :rolleyes:
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  15. Slimepuppy

    Slimepuppy New Member

    7
    0
    11
    In the for loop you have for (i=i; i<=n; i++) you put i instead of 1 easy mistake as the rest of the code is fine. Everyone hates when they have a mistake and you just can't see the error, that's why working in groups is such a good idea people are never self-critical at times.
     
    Certifications: Degree in Computer Science
  16. soundian

    soundian Gigabyte Poster

    1,460
    71
    107
    Although the "for (i=i;" is a mistake, it won't impact on the final answer if i is initialised (as it should have been) to one (or zero). It should be changed though, that type of mistake can cause a world of pain in a more complex function.
     
    Certifications: A+, N+,MCDST,MCTS(680), MCP(270, 271, 272), ITILv3F, CCENT
    WIP: Knuckling down at my new job
  17. Mof

    Mof Megabyte Poster

    526
    2
    49
    Wish I had seen this post earlier I could have had some rep points.:biggrin
     
    WIP: C++ and A+

Share This Page

Loading...