Just starting out with arrays and I am confused.

This will be a pretty long post sadly :( I have 10 exercises due on Sunday night for my CS162 class and I am thoroughly lost with arrays. I have read the entire chapter in our book and read some stuff online, but my instructors instructions still confuse me. They are so vague to me that I don't know what I'm suppose to be doing. Its a purely online class and the professor takes a day at least to respond (and most of the time the response is not very clear), which is something I don't have time for this week. So if possible, I would like to confirm that I did the first exercise correctly here, and then ask some questions on my second exercise.

The first exercises problem statement says this:

Provide array type declarations for representing the following:

-A group of rooms (living room, dining room, kitchen and so on) that have a given area

-A group of rooms as in the previous statement, but the array elements should indicate whether the room is carpeted

-Elementary school grade levels (0 through 6, where 0 means kindergarten) with a given number of students per grade
-A selection of colors (strings) representing the eye color of five people

-A new answer for the previous, assuming each array element stores an enumerator from the enumeration type:
typedef color = {blue, green, hazel, brown, black};

-An array daysInMonth with 31 number of days in January) in element 0, 28 (number of days in February) in element 1, and so on


My code that I got for this problem of declarations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <cstdlib>
#include <iostream>

using namespace std;

enum color {blue, green, hazel, brown, black};

int main()
{
    string room[4] = {"Living Room","Kitchen","Dining Room","Bedroom"}; //Holds the name of the room
    int roomArea[4] = {300,150,100,250};        //The area of each room.
    bool carpeted[4] = {true,false,false,true}; //True is there is carpet, false if not.

    int gradeLevel[7] = {0,1,2,3,4,5,6};        //Grade levels
    int studentsPerGrade[7] = {25,50,100,125,175,160,200}; //Students in each grade level.

    string eyeColor[] = {"Blue","Green","Green","Green","Brown"};   //My original eyeColor list.

    color eyeColor2[] = {blue, green, hazel, brown, black};         //enum eye color list.


    int daysInMonth[] = {31,28,31,30,31,31,31,31,31,31,31,31};      //Days in each month.

    system("PAUSE");
    return EXIT_SUCCESS;
}



This compiles fine, but I don't know if that is what he wanted.


The second exercises says this:

Write a program to store in string reverse the characters in string message, and to display "Is a palindrome" if message and reverse contain the same string. Provide input statements that will read values into both data items, and will let you repeat the reading, reversing, and displaying until the user indicates a desire to exit the program.

Solving the Problem:

Use the Exploration Journal to develop and document a solution design for this program. It does NOT need to be terribly elaborate, as the key objective is to practice accessing elements of the two string data items directly in order to accomplish the reversing action. Remember that strings can be compared directly, although they can also be compared character by character. If you do this, remember that one of the requirements for equality of strings is equality of length (which should not be a problem is this situation).



Not only am I confused with what this problem is asking me to do, I also have no idea how to take the end of the message array and put it into the first space of the reverse array. This is the code I have for the problem, but it doesn't work correctly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    char message[20], reverse[20];
    string repeat;              //If the user wants to repeat.
    char letter;
    int position = 0;

    do
    {
        cout << "Enter in a word: ";
        cin >> message;

        for(int i = 20; i > -1; i--)
        {
            letter = message[position];

            reverse[i] = letter;

            position++;
        }


        //Checking to see if the two words are the same.
        if(message == reverse)
        {
            cout << "The word is a palindrome." << endl;
        }
        else
        {
            cout << "The word is not a palindrome." << endl;
        }

        cout << "Would you like to enter in a new word (Yes or No)?";
        cin >> repeat;

    }while (repeat == "yes" || repeat == "Yes");


    system("PAUSE");
    return EXIT_SUCCESS;
} 




And finally, I'm a bit confused on how to send and return arrays to functions.

Thank you anyone who can help!

The first solution seems fine.

For the second solution, you need to do some work. Your loop initialization is doubly wrong. First of all, you have it start at 20, but the highest possible index of 'message' is 19, not 20 (remember that the first index of an array is always 0, not 1). Also, 'message' isn't always going to be 20 characters long. If you're going to use character arrays as opposed to strings, you'll probably need to make use of the strlen function which is part of the cstring library. Here's an example of how to use it and what it does:

1
2
3
4
5
6
7
#include <cstring>

int main()
{
    char message[]="text";
    cout<<strlen(message);
}


4


As for sending and returning arrays to functions, if you are planning to send an array to a function and edit that array, there is no need to return the edited array, since what you are actually sending to the function is the address of the array, not a copy of its contents:

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    void editArray(char A[]);
    char array[]="text";
    editArray(array);
    cout<<array;
}

void editArray(char A[])
{
    A[0]='a';
}


aext


If you want to return a completely new array that you created in the function, I don't think this is possible, unless your function returns a pointer that points to the address of the newly created array. But it'd probably be easier to declare the array globally.
Last edited on
Ok, so this is my new code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string message, reverse;
    string repeat;              //If the user wants to repeat.
    char letter;
    int position = 0;

    do
    {
        cout << "Enter in a word: ";
        cin >> message;


        for(int i = message.length(); i > 0; i--)
        {
            letter = message[position];

            reverse[i] = letter;

            //Outputting each value of both strings for debugging.
            cout << "message: " << message[position] << endl;
            cout << "reverse: " << reverse[i] << endl;

            position++;
        }


        //Checking to see if the two words are the same.
        if(message == reverse)
        {
            cout << "The word is a palindrome." << endl;
        }
        else
        {
            cout << "The word is not a palindrome." << endl;
        }

        cout << "Would you like to enter in a new word (Yes or No)?";
        cin >> repeat;

    }while (repeat == "yes" || repeat == "Yes");


    system("PAUSE");
    return EXIT_SUCCESS;
}


And I am I still getting the incorrect output:


Enter in a word: mom
message: m
reverse: m
message: o
reverse: o
message: m
reverse: m
The word is not a palindrome.
Would you like to enter in a new word (Yes or No)?
no
Press any key to continue . . .

Process returned 0 (0x0)   execution time : 2.998 s
Press any key to continue.
Okay, let's consider a word that's not a palindrome, like "word". So if message="word", message.size()=4. Thus, the for loop starts at i=4. It ends at i=1.

On the first loop, letter=message[0]='w' and reverse[i]=reverse[4]='w'.
On the last loop, letter=message[3]='d' and reverse[i]=reverse[1]='d'

So 'reverse' ends up being a string that has no element in it's first index (i.e. reverse[0] is empty). Furthermore, I think you'll have to include the null character at the end of the string, which is '\0'.
Alright, I've got this now as my for loop:

1
2
3
4
5
6
7
8
9
10
11
12
        for(int i = message.length(); i > 0; i--)
        {
            letter = message[i-1];

            reverse[position] = letter;

            //Outputting each value of both strings.
            cout << "message: " << message[i-1] << endl;
            cout << "reverse: " << reverse[position] << endl;

            position++;
        }


I'm not exactly sure how to implement the '\0' though....
I could be wrong but it might not be possible to assign content to an undeclared string by using the dereference operator []. I think you would need to include string class functions, which you probably haven't learned yet.

Just go back to using character arrays and replace message.length() with strlen(message). Then you'll need to include the <cstring> library. And you can implement the '\0' by adding reverse[strlen(message)]='\0'; on the next line after the for loop. That way the program knows where the string ends. Tell me if that works.

EDIT: I know for sure it will work if you use strings for 'message' and 'reverse', and if you replace reverse[position]=letter; with reverse.push_back(letter);. Then you'd also have to include a reverse.clear(); before the for loop to empty reverse every time the user enters a new word.

1
2
3
4
5
6
7
8
9
10
11
string message, reverse;
char letter;
.
.
.
reverse.clear();
for(int i = message.length(); i > 0; i--)
{
    letter = message[i-1];
    reverse.push_back(letter);
}


Also, while using character arrays, strlen(message), and the null character after the for loop will get 'message' and 'reverse' to equal one another, the problem then lies with the line if(message == reverse);, which I think is checking to see if the addresses, and not the content, of the arrays are the same. So if you use arrays, you'd have to check element by element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <cstring>
.
.
.
char message[20], reverse[20];
int position=0;
bool elementNotEqual=false;
char letter;
.
.
.
for(int i = strlen(message); i > 0; i--)
{
    letter = message[i-1];
    reverse[position] = letter;
    position++;
}
position=0;
reverse[strlen(message)]='\0';
for(int i=0;i<strlen(message);i++)
{
    if(message[i]!=reverse[i])
        elementNotEqual=true;
}
if(elementNotEqual==true)
{    
    cout<<"Not a palindrome";
    elementNotEqual=false;
}
else
    cout<<"Is a palindrome";


Either way works.
Last edited on
Alright, I made your changes, and no difference.... my current code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <cstdlib>
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char message[20], reverse[20];
    string repeat;              //If the user wants to repeat.
    char letter;
    int position = 0;

    do
    {
        cout << "Enter in a word: ";
        cin >> message;


        for(int i = strlen(message); i > 0; i--)
        {
            letter = message[i-1];

            reverse[position] = letter;

            //Outputting each value of both strings.
            cout << "message: " << message[i-1] << endl;
            cout << "reverse: " << reverse[position] << endl;

            position++;
        }

        reverse[strlen(message)] = '\0';
    

        //Checking to see if the two words are the same.
        if(message == reverse)
        {
            cout << "The word is a palindrome." << endl;
        }
        else
        {
            cout << "The word is not a palindrome." << endl;
        }

        cout << "Would you like to enter in a new word (Yes or No)?";
        cin >> repeat;

    }while (repeat == "yes" || repeat == "Yes");


    system("PAUSE");
    return EXIT_SUCCESS;
}


And my output:


Enter in a word: word
message: d
reverse: d
message: r
reverse: r
message: o
reverse: o
message: w
reverse: w
The word is not a palindrome.

Would you like to enter in a new word (Yes or No)?yes
Enter in a word: mom
message: m
reverse: m
message: o
reverse: o
message: m
reverse: m
The word is not a palindrome.

Would you like to enter in a new word (Yes or No)?no
Press any key to continue . . .

Process returned 0 (0x0)   execution time : 16.830 s
Press any key to continue.



This is really starting to get to me. I have 10 exercises and 2 homework assignments to do for this class by Sunday at 10pm and all of them except for exercise 01 and 03 have been exactly like this. It's confusing the hell out of me and I've already worked on these problems for a good 6+ hours and I'm not even close to being done.
Last edited on
Look at my edit in my previous post.

Basically, if you keep it that way, you'll have to reset 'position' to 0 after the for loop ends in case the user wants to enter another word, and you have to check both character arrays element by element, which I show how to do above.

I know for sure that will work. I tried it.
Last edited on
Thank you so much! It finally works! I don't know how I would have ever solved this problem without your help since nothing like this is even mentioned in the book.

Now I am off to struggle with the other problems... -.-
Last edited on
Topic archived. No new replies allowed.