User Defined Functions - C++

Discussion in 'Software' started by G_M_1, Jun 30, 2004.

  1. G_M_1

    G_M_1 Private E-2

    Okay so I'm trying to write my own function that will display the sum of all numbers up until the number inputted by the user.
    Ex.
    input = 5
    the function will display
    1+2+3+4+5.

    So I'm needing to tell the function to add the sum + 1 until it gets to that given number, then stop. But I'm having trouble with that. I tried using a for loop.... but it's not really working for me. Any suggestions?
     
  2. G_M_1

    G_M_1 Private E-2

    okay, pretty much figured it out. here's what i got.


    #include <iostream>
    using namespace std;

    void displaySumOneToN( int nthDigit );
    int main(void)
    {
    int number = 0;
    cout << "Enter a number to sum: ";
    cin >> number;
    displaySumOneToN( number );

    return 0;
    }

    void displaySumOneToN( int nthDigit )
    {
    int total = 0;
    for( int i = 0; i <= nthDigit; i++ )
    {
    total = total + i;
    }
    cout << "The sum of all numbers up to " << nthDigit << " is: " << total << endl;
    }





    i was wondering if it's possible to display all of the numbers that are added up to the inputted number? instead of just the sum of all those numbers...
     
  3. micr0dv8

    micr0dv8 Private First Class

    not sure exactly what you mean but can't you just put a
    cout << i;
    in your loop?
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds