GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 04-Dec-2004, 20:56
brookeville brookeville is offline
Junior Member
 
Join Date: Oct 2004
Posts: 56
brookeville is on a distinguished road

Function and Array (w/ reference variables) question


Hello everyone,

I am in need of help with a program I'm stuck on. The culprit seems to be using reference variables to pass an array's contents. Please note that this program was not assigned; it is a sample program from the textbook and is completely for my own knowledge so I can get comfortable with using reference variables. I am very confused with using them.

The program is supposed to assign/initialize the number of days in each month of the year to an array in one function. And it should have another function that asks the user to enter 1-12, corresponding to the month number. (i.e. Month 1 is January, and has 31 days). I have already done that work, but the problem is referencing the days array in the getMonth function.

Here is what I have so far:
CPP / C++ / C Code:
#include <iostream>
using namespace std;

//Function prototypes
void initArray();
void getMonth();

int main()
{
	initArray();
	getMonth();
	
	return 0;
}

   /******************************************************************************/
  /* Definition of function initArray(). This function initializes an array     */
 /*     named days with the number of days that are in each month of the year. */
/******************************************************************************/

void initArray()
	
{
	//declare an array named days initialized with # of days in each month. 
	int days[12] = {31, 28, 31, 30,
					31, 30, 31, 31,
					30, 31, 30, 31};
}

	  /*******************************************************************************/
   /*  Definition of getMonth(). This function asks the user to enter a month     */
  /*  number, verifies that it is between one and twelve, and outputs how many   */
 /* days are in the month.														                          */
/*******************************************************************************/
void getMonth()
{
	int month_number; //declare month_number variable
	int subscript; //declare subscript variable

	
	cout << "Enter a month number: ";
	cin >> month_number; //Enter month number

	while (month_number < 1 || month_number > 12) 
	//while month is less than one or greater than 12...
	{
		cout << "You have entered an invalid month.\n";
		cout << "Please re-enter a month from 1 to 12: ";
		cin >> month_number;
		//...display an error message and ask user to re-enter the month
	}

	subscript = month_number - 1; 
	//subtract one from month_number and store in subscript. This value will be used
	//as the subscript to reference the appropriate number of days. 
		
	cout << "Month " << month_number << " has " << days[subscript] << " days.\n\n";
	//output how many days are in the month
}

It should output the number of days in the month corresponding to the month number entered. I have tried a lot of reference variable combinations, none of which were successful, but I deleted them for the sake of providing a basic outline of the program. I am confused with how I should go about programming this and any help or suggestions would be greatly appreciated. Many thanks!
  #2  
Old 05-Dec-2004, 01:21
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,243
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all
Quote:
Originally Posted by brookeville
I have tried a lot of reference variable combinations, none of which were successful, but I deleted them for the sake of providing a basic outline of the program.
Well, put one of your attempts back in so we have some idea what you don't understand. Pick one that seems to be close. We can't help if we don't know what your problem is.

And welcome back!
__________________

Age is unimportant -- except in cheese
  #3  
Old 05-Dec-2004, 04:02
nkhambal nkhambal is offline
Regular Member
 
Join Date: Jul 2004
Location: CA USA
Posts: 313
nkhambal is a jewel in the roughnkhambal is a jewel in the rough
Hi,

You are declaring and initializing your days array in initArray() function. days[] has a local scope inside initArray() function. Its not available to use outside, unless it is declared globally or is part of getMonth() function. I would recommend following approach.

CPP / C++ / C Code:
void initArray(int arr[]);
void getMonth();

void initArray(int arr[12])
  
{
  //declare an array named days initialized with # of days in each month. 
  arr[] = {31, 28, 31, 30,
          31, 30, 31, 31,
          30, 31, 30, 31};
}


void getMonth() 
{

int days[12];

initArray(days);  //Declare array inside getMonth() and initialize it by passing it to initArray() function. Now its available in getMonth() for further use.

//..rest of the code for getMonth().
}

int main() 
{
getMonth();  //initArray() is called inside getMonth() so we needn't call it here.
}
  #4  
Old 05-Dec-2004, 09:50
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,709
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by nkhambal
Hi,
...
CPP / C++ / C Code:
void initArray(int arr[12])
  
{
  //declare an array named days initialized with # of days in each month. 
  arr[] = {31, 28, 31, 30,
          31, 30, 31, 31,
          30, 31, 30, 31};
}

Well, this won't work. You are trying to assign an array's contents. This is illegal syntax, and won't compile. (Did you try it?)

Brookeville's syntax was at least correct, but by itself, it won't lead to anything worth while.

CPP / C++ / C Code:
void initArray()
  
{
  //declare an array named days initialized with # of days in each month. 
  int days[12] = {31, 28, 31, 30,
          31, 30, 31, 31,
          30, 31, 30, 31};
}

This works for initializing an array, but the same syntax can't be used for assigning values to array elements in an executable program statement.

Brookeville:
Maybe you are getting confused by the terminology "reference variables". In C++, the ability to pass variables "by reference" is new, and for simple examples has no substantive advantage over using pointers as function arguments.

A little more terminology: In C and in C++, when you use the name of an array as a function argument, you are actually passing a pointer to the first element of the array. Therefore, arrays are passed by reference. To pass an array by value, declare a structure with the array as its only member.

Here's an example of using a function that initializes an array. I can't think of a circumstance where I would actually do this, but for instructional purposes, maybe it is a jumping-off point.

At least it shows how to initialize arrays and copy elements of one array to another, and it compiles and prints out some results.

Note that this program would be the same in C as C++ (except you would use #include <stdio.h>, delete the "namespace" statement, and use printf() with appropriate format specifiers in place of the cout << stuff --- well, that's pretty much the same.)

CPP / C++ / C Code:
#include <iostream>

using namespace std;

int main()
{
  void init_days(int []); // function prototype

  int days_of_month[12];

  char *month_name[12] = {"January",   "February", "March",    "April",
                          "May",       "June",     "July",     "August",
                          "September", "October",  "November", "December"};

  init_days(days_of_month); // this stores the days in the array days_of_month[]

  for (int i = 0; i < 12; i++) {
    cout << "Number of days in " << month_name[i] << " = " 
         << days_of_month[i] << endl;
  }

  return 0;
}

void init_days(int dm[]) 
{
  int days[12] = {31, 28, 31, 30,
                  31, 30, 31, 31,
                  30, 31, 30, 31};

  for (int i = 0; i < 12; i++) {
    dm[i] = days[i];
  }
}


Note the two places where I initialized arrays.

In main(), I have an array of pointer to char. Each element is a pointer, and the value is the address of the indicated string literal.

In init_days() I have an array of int. Each element is an int, and is set to the indicated value. This array is local to this function and has no visibility outside of the function (in C and C++ termonilogy: it falls "out of scope"). I pass the name of an array to this function, and set values of each element to the value from the local array.

A final note: the function init_days() works in this program, but I would have to classify this as a very dangerous function for general use. Why do I say this? Well, the function copies twelve ints into an array whose address gets passed to it. There is no way for the function to know if this is OK. That is, whoever called it must pass an argument that points to an array that can hold (at least) 12 ints.

I'll repeat this: there is no way (no way) that a function can know the size of an array that was passed as an argument. That may not mean much to you right now, but some day, not today, not tomorrow, but some day, the importance of this will fall on you and after that, you won't forget it.

Regards,

Dave
Last edited by davekw7x : 05-Dec-2004 at 10:21.
  #5  
Old 05-Dec-2004, 14:48
nkhambal nkhambal is offline
Regular Member
 
Join Date: Jul 2004
Location: CA USA
Posts: 313
nkhambal is a jewel in the roughnkhambal is a jewel in the rough
Oouch..yes it wrong..my apology...I didn't test it. I guess it just should have been,
CPP / C++ / C Code:
void initArray(int arr[12]) 
{
   arr[0]=31;
   arr[1]=28;
   arr[2]=31;
   arr[3]=30;
   arr[4]=31;
   arr[5]=30;
   arr[6]=31;
   arr[7]=31;
   arr[8]=30;
   arr[9]=31;
   arr[10]=30;
   arr[11]=31;
}

I think i should be adding a standard disclaimer in my each post.

Good day..
  #6  
Old 05-Dec-2004, 19:09
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,709
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by nkhambal
]

I think i should be adding a standard disclaimer in my each post.

Good day..

Your method of simply assigning values is certainly better than copying from a local variable the way that my example did. I was just trying to show how such things could be done if a person really wants to.

My standard disclaimer: Your Mileage May Vary.

Regards,

Dave
  #7  
Old 05-Dec-2004, 21:18
brookeville brookeville is offline
Junior Member
 
Join Date: Oct 2004
Posts: 56
brookeville is on a distinguished road
Thanks everyone for your help thus far, I really appreciate it.

Dave, in your example program above, the one thing that confuses me in working with functions is how to prototype functions and function headers that actually "work." I notice you prototyped the function void init_days(int []); and later used the header void init_days(int dm[]). The thing that confuses me is where the dm array comes from. I know dm[] must be an integer array, because that is how it is prototyped. But since dm is not "defined" anywhere in the program, (well, except in the function header), I have trouble seeing how and where it is passed by reference.

As for my program, I am not making much progress; the purpose of it is to use two separate functions to do two different things, but in the following program I have defeated that very purpose:

CPP / C++ / C Code:
#include <iostream>
using namespace std;

//Function prototypes
void initArray();
void getMonth();

int main()
{
	getMonth();
	
	return 0;
}

   /******************************************************************************/
  /* Definition of function initArray(). This function initializes an array     */
 /*     named days with the number of days that are in each month of the year. */
/******************************************************************************/



	/*******************************************************************************/
   /*  Definition of getMonth(). This function asks the user to enter a month     */
  /*  number, verifies that it is between one and twelve, and outputs how many   */
 /* days are in the month.														*/
/*******************************************************************************/

void getMonth()
{
	//declare an array named days initialized with # of days in each month. 
	int days[12] = {31, 28, 31, 30,
					31, 30, 31, 31,
					30, 31, 30, 31};

	
	int month_number; //declare month_number variable
	int subscript; //declare subscript variable

	
	cout << "Enter a month number: ";
	cin >> month_number; //Enter month number

	while (month_number < 1 || month_number > 12) 
	//while month is less than one or greater than 12...
	{
		cout << "You have entered an invalid month.\n";
		cout << "Please re-enter a month from 1 to 12: ";
		cin >> month_number;
		//...display an error message and ask user to re-enter the month
	}

	subscript = month_number - 1; 
	//subtract one from month_number and store in subscript. This value will be used
	//as the subscript to reference the appropriate number of days. 
		
	cout << "Month " << month_number << " has " << days[subscript] << " days.\n\n";
	//output how many days are in the month
}

What I am doing is not using the initArray function at all, and I still can't see how to access that function's contents. If I initialize the number of days of each month to an array defined within initArray, it stays local to initArray. And the other function, getMonth does all the work. Anything else should I try instead?
  #8  
Old 05-Dec-2004, 21:34
brookeville brookeville is offline
Junior Member
 
Join Date: Oct 2004
Posts: 56
brookeville is on a distinguished road
Also, with a few modifications to nkhambal's program, I have come up with this:
CPP / C++ / C Code:
#include <iostream>
using namespace std;

void initArray(int[]);
void getMonth();

int main() 
{
getMonth();

return 0;
}


void initArray()
  
{
  //declare an array named days initialized with # of days in each month. 
  int days[12] = {31, 28, 31, 30,
          31, 30, 31, 31,
          30, 31, 30, 31};
}

void getMonth() 
{

int days[12];

initArray();  //Declare array inside getMonth() and initialize it by passing it to initArray() function. Now its available in getMonth() for further use.
int month_number; //declare month_number variable
 int subscript; //declare subscript variable

  
  cout << "Enter a month number: ";
  cin >> month_number; //Enter month number

  while (month_number < 1 || month_number > 12) 
  //while month is less than one or greater than 12...
  {
    cout << "You have entered an invalid month.\n";
    cout << "Please re-enter a month from 1 to 12: ";
    cin >> month_number;
    //...display an error message and ask user to re-enter the month
  }

  subscript = month_number - 1; 
  //subtract one from month_number and store in subscript. This value will be used
  //as the subscript to reference the appropriate number of days. 
    
  cout << "Month " << month_number << " has " << days[subscript] << " days.\n\n";
  //output how many days are in the month

}

There are no errors compiling or executing, but the wrong data is output. I will see if I can work around this.
  #9  
Old 05-Dec-2004, 22:38
nkhambal nkhambal is offline
Regular Member
 
Join Date: Jul 2004
Location: CA USA
Posts: 313
nkhambal is a jewel in the roughnkhambal is a jewel in the rough
Hi Brookeville,

You didn't read the comments on the top in my post. The problem here is with the initArray(). The array days[] in initArray() is not same as array days[] in getMonth() function. Array days[] in initArray() function has local scope and it is not available in getMonth(). The array days[] declared in getMonth() is not initialize and has no values. Hence we need to pass array days[] in getMonth() to initArray() as an argument by reference (arrays as always passed by reference to function),so that it is initialized to the required values and its values are available in getMonth().

Good luck..
  #10  
Old 05-Dec-2004, 23:20
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,243
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all
Quote:
Originally Posted by brookeville
Dave, in your example program above, the one thing that confuses me in working with functions is how to prototype functions and function headers that actually "work." I notice you prototyped the function void init_days(int []); and later used the header void init_days(int dm[]). The thing that confuses me is where the dm array comes from. I know dm[] must be an integer array, because that is how it is prototyped. But since dm is not "defined" anywhere in the program, (well, except in the function header), I have trouble seeing how and where it is passed by reference.
The prototype is simply a copy of the function definition placed at the top of the file. You can even remove the variable names. For example the following function:
CPP / C++ / C Code:
int ReturnLowestInteger(int val1, int val2)
{
    if (val1 < val2)
        return val2;
      else
        return val2;
}
the prototype would be
CPP / C++ / C Code:
int ReturnLowestInteger(int val1, int val2);
or
CPP / C++ / C Code:
int ReturnLowestInteger(int, int);

Dave did not need to specify the dm in the header file.


Quote:
Originally Posted by brookeville
As for my program, I am not making much progress; the purpose of it is to use two separate functions to do two different things, but in the following program I have defeated that very purpose:

[code here]

What I am doing is not using the initArray function at all, and I still can't see how to access that function's contents. If I initialize the number of days of each month to an array defined within initArray, it stays local to initArray. And the other function, getMonth does all the work. Anything else should I try instead?

Then in main(), simply define the days per month array but don't load any values. Pass the address of the array to initArray(), and load the values in the function. An example:

CPP / C++ / C Code:
#include <stdio.h>
void initSequence(int *);

int main()
{
    int j;
    int seq[10];    // array to hold the first 10 sequence numbers

    initSequence(seq);
    for(j=0; j<10; j++) printf("%d ", seq[j]);
    return 0;
}

void initSequence(int *p)    // pass in the address of seq as 'p'
{
    int j;
    p[0] =   0; 
    p[1] =   1;
    for (j=2; j<10; j++)
    {
         p[j] = p[j-1] + p[j-2];
    }
}
__________________

Age is unimportant -- except in cheese
 
 

Recent GIDBlogObservations of Iraq by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Deleting elements of arrays C++ the_crazyman C++ Forum 25 30-May-2008 07:27
[Include] Doubly-linked List dsmith C Programming Language 6 14-Apr-2006 13:12
Revising Script style ?????? pepee MySQL / PHP Forum 4 14-Apr-2004 04:59
throwing an struct(with an array) through a function knakworstje C Programming Language 5 15-Feb-2004 16:20

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 16:08.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.