I am taking a C++ class, but I am having a real trouble understanding arrays which confuse me completely.
This is the first time I take a programming class, so I really need help.

I do not really understand how arrays are read and filled or how to use for loops with them.
Please, if there is someone who has something that can help me, I'd really apprecciate it.

Thanks.

Recommended Answers

All 16 Replies

An array is just about the simplest and most useful thing you can think of. Imagine a line of boxes numbered 0 to N, where N is some arbitrary number. To put something in the fifth box, you walk over to the one with the number 4 (because they start at 0), and drop the thing in it. Then you walk back to the beginning of the row. To get the thing back, you walk back to the box with 4 and grab the thing.

Let's say that thing is a number, 123. The C++ code to create a line of ten boxes numbered 0 to 9 is:

int box[10];

You can then put the thing in the fifth box like this:

box[4] = 123;

Then to get the thing back, you do the same thing, except with a spare box on the left, which we'll call thing:

int thing = box[4];

If you want every thing in the line of boxes, you go from one end to the other and grab the things in each box:

for ( int i = 0; i < 10; i++ )
  std::cout<< box[i] <<'\n';

Or you could go from the other end:

for ( int i = 9; i >= 0; i-- )
  std::cout<< box[i] <<'\n';

Just about any use of an array is some variation of the above.

Thank you for your help.

However, when I try to use functions to make a program, i do not know how to use arrays.

For example, now i am trying to make a program that reads a file that contains integers and put them to an array, then the program has to read the numbers, and if there are two equal, it will give a warning to the user.

I am lost on how to find that duplicate!

To find a duplicate in the array, you have a few options.

One way is, make a for loop, looping the variable I from 0 to N. Then, inside that, make a loop that moves the variable J from I + 1 to N. Inside that, see if the I'th and J'th elements of the array are equal.

>when I try to use functions to make a program, i do not know how to use arrays
On the surface, nothing changes. You declare an array as a function parameter the same way. The only difference is that you don't need the size, and it's a good idea to pass the size as a separate parameter:

#include <iostream>

void print_array ( int a[], int size )
{
  for ( int i = 0; i < size; i++ )
    std::cout<< a[i] <<'\n';
}

int main()
{
  int a[] = {1,2,3,4,5};

  print_array ( a, 5 );
}

>I am lost on how to find that duplicate!
Rash's suggestion is the simplest (and you should use it for now), but far from the most efficient. Just as a taste of the other options, you can sort the array and then check adjacent values to see if they're the same, or you can use an existence table:

#include <iostream>

template <typename T, int sz>
char (&array(T(&)[sz]))[sz];

void print_duplicates ( int a[], int size )
{
  int exist[10] = {0};

  for ( int i = 0; i < size; i++ )
    ++exist[a[i]];

  for ( int i = 0; i < sizeof array ( exist ); i++ ) {
    if ( exist[i] > 1 )
      std::cout<< i <<" is duplicated "
        << exist[i] - 1 <<" times\n";
  }
}

int main()
{
  int a[] = {5,4,7,6,5,6,7,8,9,3,4,5,6,7,8};

  print_duplicates ( a, sizeof array ( a ) );
}

An existence table is an array of counters, where the value in the original array is the index. By using a[0] as the index for exist, exist[5] is incremented. This is not an good method when the possible ranges are big because you need an array that can hold every possible value, but other methods (such as using a std::map can be generalized quite nicely, though you lose the linear performance. :)

Thank your very much for all your help, my program worked with the for loops. After getting the duplicates, I also had to put those integers in order, but I have done it already.

However, I have another question,
How do you compare a word with itself to check if it is a palindrome?

Do I have to use a character array or a string array because the user has to give me that word and the program has to read it backwards to check if it is or not?

If anyone has an idea please let me know!

>How do you compare a word with itself to check if it is a palindrome?
This is a classic problem, and you already have the tools to solve it. Give it a shot and see what you can come up with.

I am trying to work on this problem. I am assuming the word I am going to check is madam, but I am not sure how to compare them because my book says it is not possible to compare character arrays.

Like say word1[10], word2[10], not possible to say
if (word1==word2)

This is what i have now for entering the word and outputing it backwards, but then I am not sure how to compare them.

const int size = 5;
char pal;
cout<<"Enter a word:"<<endl;
cin>>pal;

for(int n=size; n>=0; n--)
cout<<pal[n];

look up strcmp, memcmp, strncmp, etc...

You can check for palindrome(ness) using many different techniques. You could reverse the entire string and compare the original string with the reverse to see if it is the same, but that requires knowledge of how to compare strings (winbatch has indicated some of the ways to do that). An alternative is to realize that a C style string is a null terminated char array. A palindrome is a word (or group of words), think string, that is spelled the same forward as backward. That means the first and last letter, think char, of a palindrome are the same, the second and second to last letter are the same, etc. So what? Well, you can determine the length of a word by counting the letters. You can determine the length of a string by counting the char, or, if you are familiar with strlen(), you can use it to determine the length of a C style string. strlen() returns the number of non-null char in a C style string. Once you know the length of the string you can determine what int is the largest number that is less than one half the length of the string. Then use a loop to look at each char in the first half of the string in ascending order and compare it with each char in the second half of the string starting from the end of the string and working back toward the middle. If each comparison is a match, then the string is a palindrome. The first time you have a mismatch you know the word/phrase/string isn't a palindrome and you can break out of the comparison.

Hello:

After talking to my teacher last thursday, he showed me a way to find if a word is a palindrome or not, however, I don't know why it doesn't work eventhough it looks as if it should work.

This is it:

string pal, rev;
int N;
cout<<"Enter a word to check if it is a palindrome: ";
cin>>pal;
N=pal.length();

for (int i=N-1; i>=0; i--)
{
rev[N-i-1]=pal;

}

if (pal==rev )
{cout<<endl<<pal<<" is a Palindrome";
}
else;
{
cout<<endl<<pal<<" is not a palindrome";
}
cout<<endl;

Then, I found another example similar that confuses me because this works, but it is quite similar to the one the teacher showed me.

This is it:

string s; // default initialization

cout<<"enter a word"<<endl;
cin>>s;

string r;

for(int i = s.length() - 1 ; i >= 0 ; i--)
r += s;

if(s == r)
cout << s << " is a palindrome\n";
else
cout << s << " is not a palindrome\n";

Can anyone explain me why is the first one wrong, and if there is a suggestion to make it work as the other one works?

Thank you!

>Can anyone explain me why is the first one wrong
C++ strings grow as needed, but that doesn't mean you can use any index and it'll work. You have to either force the string to grow by using push_back or +=, or resize it explicitly. In other words, this is an empty string. It has no characters, and no room to hold any characters:

string rev;

This is wrong because the string is empty, yet you're trying to use it as if it were not:

rev[N-i-1]=pal[i];

The second problem is that your else keyword has a semicolon after it, which it shouldn't. Compare this with what you wrote:

#include <iostream>
#include <string>

using namespace std;

int main()
{
  string pal, rev;
  int N;

  cout<<"Enter a word to check if it is a palindrome: ";
  cin>>pal;

  N=pal.length();
  rev.resize(pal.length());

  for (int i=N-1; i>=0; i--)
  {
    rev[N-i-1]=pal[i];
  }

  if (pal==rev )
  {
    cout<<endl<<pal<<" is a Palindrome";
  }
  else
  {
    cout<<endl<<pal<<" is not a palindrome";
  }

  cout<<endl;
}

Thank you very much,

I see I was returning an empty statement after the else, but tell me. Is resize () a function that comes with a specific library?

As well, tell me when I want to enter for example a sentence and then find an integer in it so I can replace it with a its name in words, can I still use a string by itself, or do I have to use a string array to be able to read each separate word?

Or if I have to put different names in order it confuses me if I have to use a single string for each name or not?

There are some examples similar in my book, but unfortunately I left it in school last thursday, so now I am all mixed up!

>Is resize () a function that comes with a specific library?
It's a member function of the string class, which I assumed that you were using because you declared pal and rev as string.

>can I still use a string by itself, or do I have to use a string array to be
>able to read each separate word?
You can do either, though you'll find life to be much simpler if you use an array of strings, one for each word. Otherwise you get into tokenizing and all of that muck. But replacing an integer with it's word representation isn't exactly the simplest of projects if you intend to do it right.

>Or if I have to put different names in order it confuses me if I have to
>use a single string for each name or not?
It's much easier to break the string up into an array (or better, a vector) of separate words if you want to re-order them.

This is the code I have for the names sorted, but it doesn't work completely.

I was using a similar where we had to sort words without using arrays!

I will try to debug it to see what is going wrong!

#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;
void Swap (string& x, string& y)  //SWAP FUNCTION
{
  string temp;
  temp=x;
  x=y;
  y=temp;
}

void Sort (string name[], int size)   //SORT FUNCTION
{
  string smallest;
  int small_pos;
  for (int i=0; i<size-1; i++)
  {
    smallest=name[i];
    for(int k=i; k<size; k++)

      if (name[k]<=name[i])
      {
        small_pos=k;
        smallest=name[k];
      }

      Swap (name[i], name[small_pos]);
  }     
}

int main(int argc, char *argv[])   // MAIN PROGRAM
{
  int SIZE=10;
  string names[SIZE];
  cout<<"Enter 10 names:"<<endl;
  for (int n=0; n<SIZE; n++)
    cin>>names[n];

  Sort (names, SIZE); // CALLING SORT FUNCTION

  cout<<"Sorted names are:"<<endl;

  for (int k=0; k<SIZE; k++)
    cout<<names[k]<<endl;

  system("PAUSE");
  return EXIT_SUCCESS;
}

Nooooooooo!

I can't see where the error is!

I even have a similar program that sorts numbers. It has the same structure. The only difference is that this uses string arrays instead of int array.

However, It does not work as it should.

I even tried to do swap and names by hand using the for loops, but I can't find the problem because if I do it by hand it works!

Thanks God I found the error!

It was that in the second for loop inside the Sort function I was using the wrong variable to swap!

if (name[k]<=smallest)   //Here instead of saying
                                 // name[k]<=smallest
                                 //I said name[k]<=name[n]
  { small_pos=k;
      smallest=name[k];
    }

Now, i am going to try to work on my problem that has to get a sentence and if it has a integer change it to words.

Ex:

This is test 3.

Would say:

This is test three.

I'll work on it, but if anyone has an idea I'll happily accept it!

Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.