# Variable not initialized? Code help!

• Feb 21st 2013, 12:57 PM
sakonpure6
Variable not initialized? Code help!
I have the following code that calculates how much it costs to talk on the phone during the day evening and weekends for two plans. However the code malfunctions! What am I missing or need to add? Thank you for your help!

Code:

```#include <iostream>using namespace std; int main () {         int x;         int y;         int z;         cout<<"Number of daytime minutes?:  ";         cin>>x;         cout<<"Number of evening minutes?:  ";         cin>>y;         cout<<"Number of weekend minutes?:  ";         cin>>z;                 // Do i need to do this?! //int a; //int s; //int d; //int totalw; // //int f; //int g; //int h; //int totalq;         if(x>=100)                 int a=x*25;         if(y>=1)                 int s=y*15;         if(z>=1)                 int d=z*20;         if(x>=100)                 int totalw=a+s+d;         else                 int totalw=s+d;         if(x>=250)                 int f=x*45;         if(y>=1)                 int g=y*35;         if(z>=1)                 int h=z*25;         if(x>=250)                 int totalq=f+g+h;         else                 int totalq=g+h;         cout<<"Plan A will cost "<<totalq<<" cents."<<endl;         cout<<"Plan B will cost "<<totalw<<" cents."<<endl;         if(totalq>totalw)                 cout<<"Plan B is cheapest."<<endl;         else                 cout<<"Plan A is cheapest."<<endl;         if(totalq==totalw)                 cout<<"Plan A and B are the same price."<<endl; }```
• Feb 21st 2013, 01:20 PM
emakarov
Re: Variable not initialized? Code help!
First, "using namespace std" should be on the following line. Second, yes, you have to declare variables up front, not inside an if. You can declare several variables at once: e.g., "int a, s, d;". Go again over the concept of the scope of a variable.

To add: "the code malfunctions" is a typical complaint that conveys no information except that something is wrong. It, in fact, implies that the code compiles but runs incorrectly, which is not the case. It would be much more informative to say, "The compiler complains that cin, cout, a, s, and other variables are not declared".
• Feb 21st 2013, 01:21 PM
ILikeSerena
Re: Variable not initialized? Code help!
Hi sakonpure6! :)

When you write:
Code:

```    if(x=>100)         int a=x*25;```
you have limited the scope of "a" to the if-statement.
Afterward the variable "a" is not accessible anymore.

In other words, yes, you need to declare those variables.
And you also need to remove "int" from the if-statement, because they "hide" the actual declarations, and make sure you can't get to the result anymore.
Finally, you need to initialize those variables to zero, since otherwise they may be uninitialized and contain garbage.
• Feb 21st 2013, 02:14 PM
sakonpure6
Re: Variable not initialized? Code help!
alright thank you i will give it a go!