simple program for addition

Sep 1, 2009 at 8:46am
i have this code where I was trying to make simple program for addition.
Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;
int a;
int b;
int result = a + b;

int main() 
    {
          cout<<"Enter first number:\n";
          cin >> a;
          cout <<"Enter the second number:\n";
          cin>> b;
          cin.ignore();
          cout<<"Result is"<<"  "<<result<<endl;
          cin.get();
          return 0;
          }


The problem is I always get Restult as 0(zero)...
What is wrong with my code
Sep 1, 2009 at 9:32am
You are initializing result when a and b are equal to zero:
1
2
3
int a; // a = 0
int b; // b = 0
int result = a + b; // result = 0 + 0 = 0 
You need to set the value of result after you get the input
Sep 1, 2009 at 11:28am
Yeah, and don't use globals, you don't need to. Do it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main() 
    {
          int a;
          int b;
          cout<<"Enter first number:\n";
          cin >> a;
          cout <<"Enter the second number:\n";
          cin>> b;
          cin.ignore();
          int result = a + b;
          cout<<"Result is"<<"  "<<result<<endl;
          cin.get();
          return 0;
     }


Sep 1, 2009 at 2:49pm
ok i get it now, tnx a lot!
Topic archived. No new replies allowed.