Need help please

Apr 11, 2013 at 2:45am
I have to write a program that displays the number of days in each month. Here's what the output should look like:

"January has 31 days."
"February has 28 days."
and so on...

I'm trying to use 2 arrays and also use a loop until the user wants to stop.

This is what I have so far, but I can't get the 2nd array to work.

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

int main()
{

	int num;
	const int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; 
	char month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};


	cout << "Enter the corresponding month number (ex. January = 1): " << endl;
	cin >> num;
	num--;

	cout << month << "has " << days[num] << "days." << endl; 

	return 0;
}
Apr 11, 2013 at 3:02am
@H3avenlySoul

You were very close. Month needed to be a string array of 12. Then when you ask the user for the month, the variable num is used for both the month and the days in that month.

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

using namespace std;

int main()
{

	int num;
	const int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; 
	string month[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};


	cout << "Enter the corresponding month number (ex. January = 1): " << endl;
	cin >> num;
	num--;

	cout << month[num] << " has " << days[num] << "days." << endl; 

	return 0;
}
Apr 11, 2013 at 3:06am
It's always the little things that I miss. Thank you! How would I go about adding the loop? Do you mind helping me with that?
Apr 11, 2013 at 3:15am
@H3avenlySoul
A good way for you to add your loop would be to have the console display a message such as "Would you like to enter another month (y/n)"
Then if the user enters 'y' for yes then have it loop to the very beginning of your program again. If 'n' for no then your program just ends. Consider which loop would be best for this. Would you use a for loop, while loop, or a do...while loop?
Apr 11, 2013 at 3:27am
or by possibly using a break. something such as "(enter 0 to exit)" at the end of your original output and if the user enters 0 instead of 1-12 it will then break off from the rest of your program and simply exit.
Apr 11, 2013 at 3:30am
I got it. Thank you both for your help! It is greatly appreciated! :)
Apr 11, 2013 at 4:19am
You are very welcome. Keep up the.good work.
Topic archived. No new replies allowed.