Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"0" appearing after function is completed in C++

// This program is able take two variables`
// and apply Auto increment or decrement`
// based on the user's input and by calling a function

#include <iostream>

using namespace std;

int inc (int, int); // Increment function prototype
int dec (int, int); // Decrement function prototype

int main () 
{
    int num1, num2;
    char operation = ' ', I, D;

    cout << "Enter the first variable: ";
    cin >> num1;
    cout << "Enter the second variable: ";
    cin >> num2;
    cout << endl;
    
    cout << "Do you want Auto increment, decrement or both? (Type 'I', 'D' or 'B'): ";
    cin >> operation;
    
    if (operation == 'I') {
        cout << inc(num1,num2);
    }
    else if (operation == 'D') {
        cout << dec(num1,num2);
    }
    else if (operation == 'B') {
        cout << inc(num1,num2);
        cout << endl;
        cout << dec(num1,num2);
    }
    else {
        cout << "Error please enter 'I', 'D' or 'B' as a option" << endl;
    }

    return 0;   
}

int inc (int num1, int num2) {
    num1++; num2++;
    
    cout << "Number 1 ++ is: " << num1 << endl;
    cout << "Number 2 ++ is: " << num2 << endl;
    
    return 0;
}

int dec (int num1, int num2) {
    --num1; --num2;
    
    cout << "Number 1 -- is: " << num1 << endl;
    cout << "Number 2 -- is: " << num2 << endl;
    
    return 0;
}

I just started taking Fundamentals of programming I at college and i have this assignment and this 0 keeps appearing after the function has completed

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This happens because your inc and dec print stuff, but also return an int. You then proceed to print the return value, on these lines:

cout << inc(num1,num2);

and

cout << dec(num1,num2);

.

You can safely remove these cout << prefixes, and probably the entire return value, as it does not seem necessary to output your resuls (that happens in inc and dec).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading