14 Replies - 1332 Views - Last Post: 06 June 2011 - 10:09 AM Rate Topic: -----

#1 jawsome  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 02-June 11

Global Variables, And how not to use them

Posted 05 June 2011 - 03:52 PM

Thanks to you guys I was able to complete most of my program. However I am using "Global Variables" for some things and I am told by my professor to basically avoid them or I will get a poor grade in the class. Here is my code...do you have any suggestions on how I can do away with Global variables.

The intructor has not taught pointers yet. Is the only way to use arrays and functions the way I am using them WITHOUT pointers Global Variables?

#include <iostream>
#include <cstring> 
#include <conio.h>
#include <cmath>
/* 
Write a program that reads in the average monthly rainfall for a city for each
month of the year and then reads in the actual monthly rainfall for each of the
previous 12 months. The program then prints out a nicely formatted table show-
ing the rainfall for each of the previous 12 months as well as how much above or
below average the rainfall was for each month. The average monthly rainfall is
given for the months January, February, and so forth, in order. To obtain the
actual rainfall for the previous 12 months, the program first asks what the cur-
rent month is and then asks for the rainfall figures for the previous 12 months.
The output should correctly label the months.
There are a variety of ways to deal with the month names. One straightforward
method is to code the months as integers and then do a conversion before doing
the output. A large switch statement is acceptable in an output function. The
month input can be handled in any manner you wish, as long as it is relatively
easy and pleasant for the user.
After you have completed the above program, produce an enhanced version that
also outputs a graph showing the average rainfall and the actual rainfall for each
of the previous 12 months. The graph should be similar to the one shown in
Display 5.4, except that there should be two bar graphs for each month and they
should be labeled as the average rainfall and the rainfall for the most recent
month. Your program should ask the user whether she or he wants to see the
table or the bar graph, and then should display whichever format is requested.
Include a loop that allows the user to see either format as often as the user wishes
until the user requests that the program end..
*/
using namespace std;
int actualRain(int current);
int difCalc();
int chart();
int graph();	

int actual[12];
int average[12];

const char months[][12] = {"January","February","March","April","May","June","July","August","September","October","November","December",'\0'};
int main()
{
	int choice;
	
  
    int i = 0;
    int current=13;
    do 
    {
    cout << "What Month is it (enter the number of the month Example: 1. Jan Dec. 12) \n";
    cin >> current;
    }
    while (current > 12);

//this is where it loops to enter average
	cout<<"ENTER AVERAGE RAINFALL \n";
	cout<< " FOR EACH MONTH";
    cout << endl;
	for(int i=0; i<12; i++)
	
    	{
 	    cout << months[i]<<"  : ";	    
         cin >> average[i];
     	}
     	
       actualRain(current);
//this is where we call the function for actual
cout << "press 1 for table press 2 for graph, any other charecter to exit \n";
do
  {       
     cin >> choice;
     if (choice == 1)
     chart();
     else if (choice == 2)
     graph();
     else
     cout << "ending program \n";
  } 
  while (choice < 3);
getch();
return 0;   

}
	   
	
int actualRain(int current)
{
    
    cout<<"ENTER TOTAL RAINFALL \n";
	cout<< " FOR EACH MONTH \n";
    for(int i=(current-1); i>=1; i--)
    {
    cout<<months[i]<<"  : ";	    
    cin >> actual[i];
    }    
    
    for(int j=11; j>=current; j--)
    {
    cout << months[j]<<"  : ";	    
    cin >> actual[j];
    }    
	return 0;
}

int difCalc()
{
 int transfer;
 int transferAbs;
 int rainDifferance[12];
 for(int i=0; i<12; i++)
	
    	{
        transfer = (average[i] - actual[i]);
        transferAbs=abs(transfer);
 	    rainDifferance[i]= transferAbs;
        
     	}    
}
int chart()
{
 int transfer;
int transferAbs;
int rainDifferance[12];	
for(int i=0; i<12; i++)
	
    	{
   		transfer = (average[i] - actual[i]);
        transferAbs=abs(transfer);
 	    rainDifferance[i]= transferAbs;
 	    cout << months[i]<<"  : ";	    
        cout << actual[i] << " Difference : ";
        cout << rainDifferance[i] << endl;
     	}    
}

int graph()
{

}



Is This A Good Question/Topic? 0
  • +

Replies To: Global Variables, And how not to use them

#2 RetardedGenius  Icon User is offline

  • >>──(Knee)──►
  • member icon

Reputation: 126
  • View blog
  • Posts: 555
  • Joined: 30-October 10

Re: Global Variables, And how not to use them

Posted 05 June 2011 - 04:06 PM

You need to learn more about functions, specifically how to pass parameters by reference and the difference between passing a parameter by reference and by value. I would strongly reccommend reading Functions 1 and Functions 2. :)
Was This Post Helpful? 2
  • +
  • -

#3 Xupicor  Icon User is offline

  • Nasal Demon
  • member icon

Reputation: 249
  • View blog
  • Posts: 582
  • Joined: 31-May 11

Re: Global Variables, And how not to use them

Posted 05 June 2011 - 04:09 PM

You probably should pass your arrays into the functions, instead keeping them global. That way those functions will be more usable, because you will be able to use many different arrays with them, not just the one that you made global.
void foo(int array[]) {
    // use array
}

int main() {
    //...
    int array[12];
    foo(array);
    //...
    return 0;
}

Usually you want to pass arrays length to the function too:
void foo(int array[], size_t length);

Since there's no way to know what the size of the array is. ;) (sizeof operator will return the size of a pointer).
The above and below declarations would work the same:
void foo(int* array, size_t length);


However, since you know upfront that your array must consist of 12 elements, then you can probably omit the length parameter altogether. Maybe signify it in the function signature:
void foo(int array[12]);
Note that it only serves as a reminder, you can actually pass any 1d array to foo(), even though it says "12". ;)
Was This Post Helpful? 0
  • +
  • -

#4 RetardedGenius  Icon User is offline

  • >>──(Knee)──►
  • member icon

Reputation: 126
  • View blog
  • Posts: 555
  • Joined: 30-October 10

Re: Global Variables, And how not to use them

Posted 05 June 2011 - 04:26 PM

For arrays you must understand that they are passed by reference by default and cannot be passed by value. This is for efficiency and it makes sense as C and C++ are primarily systems programming languages. If you want to an take array as a parameter for a function and you don't want it to be modified in the process, simply prefix its declaration with const e.g.

void Foo(const int[], int length);

It is important that you pass a separate parameter that holds the length of the array, so that function knows how large it is. For example for a sorting algorithm. You may also want to read about pointers. :)

This post has been edited by RetardedGenius: 05 June 2011 - 04:28 PM

Was This Post Helpful? 1
  • +
  • -

#5 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5932
  • View blog
  • Posts: 12,857
  • Joined: 16-October 07

Re: Global Variables, And how not to use them

Posted 05 June 2011 - 04:27 PM

#include <iostream>
#include <cstring>
// bad, never use this
// #include <conio.h>
#include <cmath>

using namespace std;

// const are fine global
// and magic numbers are bad
const int MONTH_COUNT = 12;

// globals, bad
// parallel arrays, also bad
// int actual[12];
// int average[12];

struct RainFallItem { 
	int actual, average;
	int rainDifferance; // you seem to sneak this in later, might as well own it
};

typedef RainFallItem AnnualRainFall[MONTH_COUNT];


int actualRain(AnnualRainFall, int current);
int difCalc(AnnualRainFall);
int chart(AnnualRainFall);
int graph(AnnualRainFall);

const char *getMonthName(int month) {
	const char *name[MONTH_COUNT] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
	return name[month];
}

int getMonthFromUser() {
	int month;
	do {
		cout << "What Month is it (enter the number of the month Example: 1. Jan Dec. 12) \n";
		cin >> month;
	} while (month > 12 || month < 1);
	return month - 1;
}


Was This Post Helpful? 2
  • +
  • -

#6 jawsome  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 02-June 11

Re: Global Variables, And how not to use them

Posted 05 June 2011 - 05:15 PM

I get it now....I dont have to return arrays to the caller because they are pass by reference...the calling function will modify the array in the function no matter what because pass by reference...referances a specific point in memory rather that a value. If it was pass by value then the modified value would only leave the function if returned to the caller.

Is this right?
Was This Post Helpful? 0
  • +
  • -

#7 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Global Variables, And how not to use them

Posted 05 June 2011 - 05:29 PM

Quote

For arrays you must understand that they are passed by reference by default and cannot be passed by value.
Not quite true. Arrays are not passed by reference automatically though. Also, you can end up passing arrays by value, but you need to wrap them in a struct.

Quote

This is for efficiency and it makes sense as C and C++ are primarily systems programming languages.
No, it's because arrays decay to pointers in most expressions. I could have sworn I explained this to you before.
Was This Post Helpful? 1
  • +
  • -

#8 jawsome  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 02-June 11

Re: Global Variables, And how not to use them

Posted 05 June 2011 - 06:06 PM

View Postbaavgai, on 05 June 2011 - 04:27 PM, said:

#include <iostream>
#include <cstring>
// bad, never use this
// #include <conio.h>
#include <cmath>

using namespace std;

// const are fine global
// and magic numbers are bad
const int MONTH_COUNT = 12;

// globals, bad
// parallel arrays, also bad
// int actual[12];
// int average[12];

struct RainFallItem { 
	int actual, average;
	int rainDifferance; // you seem to sneak this in later, might as well own it
};

typedef RainFallItem AnnualRainFall[MONTH_COUNT];


int actualRain(AnnualRainFall, int current);
int difCalc(AnnualRainFall);
int chart(AnnualRainFall);
int graph(AnnualRainFall);

const char *getMonthName(int month) {
	const char *name[MONTH_COUNT] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
	return name[month];
}

int getMonthFromUser() {
	int month;
	do {
		cout << "What Month is it (enter the number of the month Example: 1. Jan Dec. 12) \n";
		cin >> month;
	} while (month > 12 || month < 1);
	return month - 1;
}


there is so much I am learning from this post.
Was This Post Helpful? 0
  • +
  • -

#9 Xupicor  Icon User is offline

  • Nasal Demon
  • member icon

Reputation: 249
  • View blog
  • Posts: 582
  • Joined: 31-May 11

Re: Global Variables, And how not to use them

Posted 06 June 2011 - 03:39 AM

@Oler1s True that. Arrays are arrays, but they decay to pointers in most situations as described in the standard:

ISO C++03 Standard said:

4.2 Array-to-pointer conversion [conv.array]
1 An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to an rvalue
of type “pointer to T.” The result is a pointer to the first element of the array.
Thus, arrays are not passed by value, because they aren't passed at all - they are implicitly converted to a pointer, and the pointer is passed by value.
Yes, pass by pointer is called "pass by reference" in C, but this becomes bit confusing in C++, since there are "built-in" references in C++.

edit: The issue is even more verbose in C99:

ISO C99 Standard said:

6.3.2 Other operands
6.3.2.1 Lvalues, arrays, and function designators
[...]
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a
string literal used to initialize an array, an expression that has type ‘‘array of type’’ is
converted to an expression with type ‘‘pointer to type’’ that points to the initial element of
the array object and is not an lvalue. If the array object has register storage class, the
behavior is undefined.
4 A function designator is an expression that has function type. Except when it is the
operand of the sizeof operator54) or the unary & operator, a function designator with
type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to
function returning type’’.

53) The name ‘‘lvalue’’ comes originally from the assignment expression E1 = E2, in which the left
operand E1 is required to be a (modifiable) lvalue. It is perhaps better considered as representing an
object ‘‘locator value’’. What is sometimes called ‘‘rvalue’’ is in this International Standard described
as the ‘‘value of an expression’’.
An obvious example of an lvalue is an identifier of an object. As a further example, if E is a unary
expression that is a pointer to an object, *E is an lvalue that designates the object to which E points.
54) Because this conversion does not occur, the operand of the sizeof operator remains a function
designator and violates the constraint in 6.5.3.4.

This post has been edited by Xupicor: 06 June 2011 - 04:13 AM

Was This Post Helpful? 2
  • +
  • -

#10 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Global Variables, And how not to use them

Posted 06 June 2011 - 09:22 AM

:) Oh no! Whippin' out the standards on Oler1s!

I always love it when standards' quotes start flying about in threads.
Was This Post Helpful? 0
  • +
  • -

#11 Xupicor  Icon User is offline

  • Nasal Demon
  • member icon

Reputation: 249
  • View blog
  • Posts: 582
  • Joined: 31-May 11

Re: Global Variables, And how not to use them

Posted 06 June 2011 - 09:36 AM

Well... I don't know how you interpreted my post, but I'm most definitely supporting Oler1s' point. :P

This post has been edited by Xupicor: 06 June 2011 - 09:36 AM

Was This Post Helpful? 0
  • +
  • -

#12 jawsome  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 18
  • Joined: 02-June 11

Re: Global Variables, And how not to use them

Posted 06 June 2011 - 09:37 AM

yeah so I am going to fail this class. Doesn't mean I am giving up though, you have not seen the last of me. I learned a lot already..and I plan on retaking it.

A little backstory on me. I am a PC helpdesk guy, got my bachelors degree in 2007 for networking. But it was always my dream to be a PC game developer. In highschool I took this BASIC course and was like top of the class...in College though my adviser talked me out of getting a BA in programming because I live in Chicago and they said finding a helpdesk job would be easier.

So anyways yeah I signed up with Depaul to get my Masters in Computer Game development this spring (since I already have a technical BA i have to take like 4 basic C++ course and 2 math course they start me on my masters degree requirements) . This was a homework for my first class. This was homework assignment 7. The first assignments were really easy for me to pick up...this one basically pulled everything from what we learned together..I totally bombed on it. (the advice I got in this forums helped me nearly complete it...but not in time for my professors deadline...which is OK because i had trouble on the final exam as well, so I clearly need to revisit some of the concepts. Did better on the midterm..but yeah, programming is a tough learning curve)

I am gonna probably miss the mark on the course. But I plan on retaking it in the fall. It is truly my dream to be a programmer. I want to self study over the summer so I am ready to pass this course and the advance courses in the fall...

Any advice on the best way to self study for the next 3 months?

This post has been edited by jawsome: 06 June 2011 - 09:46 AM

Was This Post Helpful? 0
  • +
  • -

#13 RetardedGenius  Icon User is offline

  • >>──(Knee)──►
  • member icon

Reputation: 126
  • View blog
  • Posts: 555
  • Joined: 30-October 10

Re: Global Variables, And how not to use them

Posted 06 June 2011 - 09:38 AM

View PostNickDMax, on 06 June 2011 - 05:22 PM, said:

:) Oh no! Whippin' out the standards on Oler1s!

I always love it when standards' quotes start flying about in threads.

Same here. I deliberately didn't go into more detail because my concise explanation could have soon swollen to a huge wall of text. I wanted to give the OP the information he needs in the short-term while pointing him to resources that will explain the rest in the necessary detail. :)
Was This Post Helpful? 0
  • +
  • -

#14 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5932
  • View blog
  • Posts: 12,857
  • Joined: 16-October 07

Re: Global Variables, And how not to use them

Posted 06 June 2011 - 10:03 AM

View Postjawsome, on 06 June 2011 - 12:37 PM, said:

Any advice on the best way to self study for the next 3 months?


Sure, steal other people's stuff... I'm only half kidding here. Cracking books will only get you so far in programming. You really have to "do it" to "get it." Once you do something ( here's the stealing part ) look at how other people did it.

Looking at an example or theory only has the amount of meaning that you bring to it. If you've never tried to solve the problem they're solving for you, it will seem kind of pointless. However, if you've tried to write a particular program, and you get to see how someone else did it, then you're primed. You've thought about the problem a lot and wished you knew the best way to attack it.

I like tic tac toe. It's a very simple thing, it can be done ten thousands different ways, and all of them are valid. Write a tic tac toe program, then search this site and see how many others have done the same. ;)
Was This Post Helpful? 0
  • +
  • -

#15 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Global Variables, And how not to use them

Posted 06 June 2011 - 10:09 AM

Quote

Any advice on the best way to self study for the next 3 months?


My all time number 1, fourstar, most important, top best advice is: Do programming!

Write programs.

One good way is to hang out here and try your hand at answering posts (amazing what researching some basic questions will get you). and if your advice is a little off, members will correct you (so I suppose it can take a little thinker skin).

But all in all the key is just to exercise your mind at solving problems via programming. Get a good book, follow some youtube video tutorials, etc. Just don't let 6months pass by without ever compiling some code.

Another good thing (although it is a little more boring and harder) is to read code. Say look though snippet programs here on DIC and see if you can pick apart how they work and why the programmer made the choices they did. -- The nice thing about reading programming is that you begin to see "bad" as well as "good" programming and begin to recognize the difference.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1