I'm new to C++. I want to know if there's any way to shorten this code.

#include <iostream>
using namespace std;

    int a, b, result;

int main () //Addition (main function of this program)
{
    
    cout << "Lets add numers\nEnter you first number\n";
    
    cin >> a; //First value
    cin.clear ();
    cin.get ();
    cout << endl;
    
    cout << "Enter your second number\n";

    cin >> b; //Second value
    cin.clear ();
    cin.get ();
    cout << endl;
    
    result = a + b; //Adds the values together
    cout << result; //Displays the result
    cout << endl;
    
    //this will check to see if result is even or odd
    if (result % 2 == 0) cout << "your result is even";
    else cout << "your result is odd";
    
    cin.clear ();
    cin.get ();
    return 0;
}

Also if you see something I did, and there's a better way for it, please explain to me how I could do it better.

>using namespace std;
You can remove this line by explicitly qualifying the std namespace on your names.

>cin.clear ();
>cin.get ();
>cout << endl;

These lines are unnecessary. Further, you can merge the input into a single prompt:

std::cout<<"Enter two numbers: ";
std::cin>> a >> b;

>cout << result; //Displays the result
>cout << endl;

These lines can be merged (and endl is often unnecessary):

std::cout<< result <<'\n';

>if (result % 2 == 0) cout << "your result is even";
>else cout << "your result is odd";

You can make use of the ternary operator here:

std::cout<<"Your result is "<< (result % 2 ? "odd" : "even") <<'\n';

>std::cout<< result <<'\n';
>std::cout<<"Your result is "<< (result % 2 ? "odd" : "even") <<'\n';

These two lines can be merged, but the line length starts getting awkward:

std::cout<< result <<"\nYour result is "<< (result % 2 ? "odd" : "even") <<'\n';

>cin.clear ();
>cin.get ();
>return 0;

These are all unnecessary.

All suggestions included:

#include <iostream>

int main()
{
  int a, b, result;

  std::cout<<"Enter two numbers: ";
  std::cin>> a >> b;

  result = a + b;

  std::cout<< result <<"\nYour result is "<< (result % 2 ? "odd" : "even") <<'\n';
}

#include <iostream>
using namespace std;
void main ()
{ int i ,j,f,y;
f=0;
y=0;
cout<<" 1st num = ";
cin>> i;
cout<<" 2nd num = ";
cin>> j;
f= i+j; //f = result
y=f/2;
if ( y= 0)
cout<<"even";
else
cout<<" odd";
}

Thank you so much, this is exactly what I wanted to know

>cin.clear ();
>cin.get ();
>cout << endl;
These lines are unnecessary.

I was told to put these in so that I can see the ending result without the program terminating itself after I got the results I asked for. Is there anything besides [ system ("pause"); ] and [ cin.clear();cin.get(); ] that I can use to achieve this?

Or is that the reason you left return 0; out? Is it needed?
I tried running it, it doesn't stay open

Edited 6 Years Ago by NickRx: Added the bottom line

1.) Use code tags, Narue said something to you already

2.)

y=f/2;
if ( y= 0)
cout<<"even";
else 
cout<<" odd";

is not even close. According to this code (if it were actually written correctly), the only even number that exists is '0'. First, you need to use the modulus operator '%' when you first assign 'y' so that you get the remainder of the integer division, not the quotient. Second, you are using the assignment operator '=' in your condition instead of the equality operator '=='. As a result, you'll always wind up with an "odd" output (because 0 == false).

3.) main() should always return an int

@NickRx:
If you need to hold the program open, add cin.get(); at the end of the program. It will then wait for you to press [ENTER]. If it's not holding it open, change it to cin.ignore(); cin.get();. Never use system(); if you can avoid it. It's inefficient, and it's a gaping security hole.

Edited 3 Years Ago by happygeek: fixed formatting

>I was told to put these in so that I can see the ending
>result without the program terminating itself

Whether that happens depends on how you run the program. It's also not as simple as you were told. If the stream is clean, all you need to do is call cin.get(). But if the stream is dirty, it gets complicated. Note that cin.clear() doesn't "flush" the input stream, it clears error flags.

>Or is that the reason you left return 0; out? Is it needed?
I left out the return statement because in standard C++, 0 is returned from main automatically. return 0; at the end is redundant.

y=f/2; //This will tell you nothing about the evenness of f
if ( y= 0) //This will always resolve to false because the assignment operator essentially returns the rvalue, which is always 0 in this case. Perhaps you meant y==0 ?
cout<<"even";
else
cout<<" odd";
}

This is a good way to avoid the costly mod operator (if this was your intention) while determining if a number is even:

bool isOdd =  result & 1;

This works because all even values have a 0 in the least significant bit, while odds have a 1 in the LSB. The bitwise operator will essentially test the LSB, and return 1 if the LSB is 1, and 0 otherwise. You can see this for yourself with this code

#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
    for( int i=0; i<14; i++ )
        cout << i << " is " << ( i & 1 ? "odd\n" : "even\n" );
    return 0;
}

This could be easily applied to this problem by using this line

cout << "your result is " << ( result & 1 ? "odd\n" : "even\n" );

That's a neat trick, I'll have to remember that...

blue: is obviously very new (not that I'm saying I'm not, cause I am), so I doubt he was considering the performance issues.

Edited 6 Years Ago by Fbody: n/a

>bool isOdd = result & 1;
I wouldn't necessarily recommend it unless you can prove that the remainder operator is noticeably slow and bitwise AND is significantly faster. Decreasing readability for dubious performance gains smacks of bad practice.

>bool isOdd = result & 1;
I wouldn't necessarily recommend it unless you can prove that the remainder operator is noticeably slow and bitwise AND is significantly faster. Decreasing readability for dubious performance gains smacks of bad practice.

Hmm.... I'll have to remember that too...

>bool isOdd = result & 1;
I wouldn't necessarily recommend it unless you can prove that the remainder operator is noticeably slow and bitwise AND is significantly faster. Decreasing readability for dubious performance gains smacks of bad practice.

On modulo: http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues

Without compiler operations, modulo is much slower than bit-wise AND. However, as noted on the above link, most compilers will optimize the difference away. As far as pad practice, isn't optimizing C an irreconcilable trade-off between readability and performance? ;)

>On modulo: http://en.wikipedia.org/wiki/Modulo_...ormance_issues
Thank you for strengthening my case. Allow me to quote from the link that you apparently didn't read very carefully (emphasis mine):

Modulo operations might be implemented such that a division with a remainder is calculated each time.

For special cases, there are faster alternatives on some hardware.

In devices and software that implement bitwise operations more efficiently than modulo, these alternative forms can result in faster calculations.

That's a lot of ass covering language that you didn't account for in your original recommendation. But it gets even better (as you noted):

Optimizing C compilers generally recognize expressions of the form expression % constant where constant is a power of two and automatically implement them as expression & (constant-1). This can allow the programmer to write clearer code without compromising performance.

In other words, this is a pretty common optimization (which I can independently confirm). Not only would it be redundant to optimize an expression that the compiler will optimize for you, it's entirely possible that you could end up confusing the optimizer and getting worse results than straightforward code.

It's not uncommon for cleverly "optimized" code to often end up slower than stupid code for that very reason. One good example is the XOR swap.

>Without compiler operations, modulo is much slower than bit-wise AND.
I assume you mean "without compiler optimizations". And yes, for the most part you're right. But don't forget that performance is relative. If % is "much slower" than &, but they both occur so fast nobody gives a rat's ass, why bother squeezing out extra performance that won't be noticed? It's wasted effort and diminishes code maintainability.

>As far as pad practice, isn't optimizing C an irreconcilable
>trade-off between readability and performance?

I think you'd be surprised. Except in extreme cases, well-written C can be both readable and fast. It's just as important to know when to optimize as it is to know how.

So let's add a caveat to your first post that addresses my concerns, and call it good: if profiling your code shows % to be a bottleneck, the & operator may be a viable alternative. But keep in mind that micro-optimizations are very rarely a big win. Better algorithms have a bigger impact than counting cycles.

Edited 6 Years Ago by Narue: n/a

>On modulo: http://en.wikipedia.org/wiki/Modulo_...ormance_issues
Thank you for strengthening my case. Allow me to quote from the link that you apparently didn't read very carefully (emphasis mine):

Actually, I have read it carefully, and my most recent visit to that link was not the first. You'll notice that I didn't contradict your reply.

In other words, this is a pretty common optimization (which I can independently confirm). Not only would it be redundant to optimize an expression that the compiler will optimize for you, it's entirely possible that you could end up confusing the optimizer and getting worse results than straightforward code.

It's not uncommon for cleverly "optimized" code to often end up slower than stupid code for that very reason. One good example is the XOR swap.

If you write a lot of cross platform code (which I do), you can't really make assumptions about the compiler that will be used to build the application for end users. It is not bad practice to use explicit optimizations rather than relying on the compiler to do it. If the optimizations are simple and clean ( such as >> & ), you can be fairly confident that the compiler won't get confused.

But don't forget that performance is relative. If % is "much slower" than &, but they both occur so fast nobody gives a rat's ass, why bother squeezing out extra performance that won't be noticed? It's wasted effort and diminishes code maintainability.

That's quite an assumption. Even minor optimizations can result in big boosts for very large problems. Saving even a nanosecond per iteration over a trillion iterations is a significant gain.

I think the whole modulo battle is quite unfortunate. I love the modulo operation because of its elegance and utility. Also, I won't argue that sacrificing readability for minor performance gains can be a minus. However, in cases where the optimizations don't hurt readability significantly, I hold that they should be used. Furthermore, comments go a long way to helping readability and maintainability, and well developed code should never rely on the maintainer's experience or prowess in the language to interpret the semantics behind the syntax.

>It is not bad practice to use explicit optimizations
>rather than relying on the compiler to do it.

The problem with many explicit optimizations is they're very specific to a platform/implementation. In assuming that the compiler won't optimize for you (not exactly a good assumption these days), you can easily end up decreasing the portability of your code. All in the name of portability. :icon_rolleyes:

>If the optimizations are simple and clean ( such as >> & ), you
>can be fairly confident that the compiler won't get confused.

a ^= b;
b ^= a;
a ^= b;

Simple, clean, even elegant. But compilers tend to get confused and don't optimize as well as the more standard swap with a temporary.

>Saving even a nanosecond per iteration over a trillion iterations is a significant gain.
Sure, if your last resort is micro-optimizations, go for it. But in every other case, make bigger changes (ie. algorithms and data structures) for bigger improvements. As a simple to understand example, you can optimize the inner loop of a bubble sort until you're blue in the face, or you can switch to a better algorithm. The latter will both improve current performance and raise the ceiling for potential optimization.

>Furthermore, comments go a long way to helping readability and maintainability
I try to discourage people from using comments as a Band-Aid. This is a bad habit to get into:

"Oh, this code is a bitch to understand. I'll just comment it instead of making it better."

>well developed code should never rely on the maintainer's experience
>or prowess in the language to interpret the semantics behind the syntax.

Indeed. In fact, weaker programmers on a team will typically be given maintenance tasks, so code should be written with the lowest common denominator in mind, if possible. And yes, I do believe that x % 2 is more commonly understood than x & 1 .

Indeed. In fact, weaker programmers on a team will typically be given maintenance tasks, so code should be written with the lowest common denominator in mind, if possible. And yes, I do believe that x % 2 is more commonly understood than x & 1 .

Hmm. For me, I was more familiar with x & 1 before x % 2 . If the general optimization is to x & 1 , what's the issue?

I know the x % 2 version has been known to cause me problems -- bringing in calls to assembly-coded library functions when unintended. And being wary of vendor optimizations, much of the code I've dealt with over the years has specifically been with optimizations off.

When I run into two equivalent idioms and one is known to cause me problems, I generally discard the one that gives me problems in favor of the other.

Hmm.

Edited 6 Years Ago by Dave Sinkula: Grrr. Done(?)

>If the general optimization is to x & 1 , what's the issue?
I really don't have any issue with it, but in my experience, the majority will understand x % 2 better than x & 1 . I'm of the opinion that the more widely understood code is better unless circumstances warrant the alternative. If most of your work involves bit bashing, x & 1 would probably be the better choice.

Comments
Danke.
This question has already been answered. Start a new discussion instead.