appending arrays

Pages: 12
I have to say that arrays are somewhat of a pain in my behind! I am doing a phase of my homework, and when I am doing this, I like to search the internet for helpful tips, but sometimes, people just post solutions to the problem without explaining what they do, which reduces my comprehension of the lesson to almost nothing.

Would anyone be kind enough to explain this solution to my homework, so that I can understand it?

I have a program with an array pointer that displays the letters of the alphabet. I need to change the code so that the program replaces every other letter with a lowercase "x." Someone, on another website, suggested adding a space parameter to the array so that it can handle an increase in size, then writing 26 strcpy statements, then using strcat for concatenation.

I could not find references to these two statements anywhere in my reading material, and it seems like overkill to accomplish this.

Is this solution really the best solution? If so, can someone explain why? If not, can someone point me in the right direction?
OK, these links lead to string manipulation, but does it work the same for elements of an array?

In my program, each letter of the alphabet is its own element.

int main()
{
array<char>^ letters = gcnew array<char>(26);
char* pletters [] = { "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", "I ", "J ", "K ", "L ", "M ", "N ", "O ", "P ", "Q ", "R ", "S ", "T ", "U ", "V ", "W ", "X ", "Y ", "Z "};
cout << "PRINTING CONTENTS OF ARRAY" << endl;
cout << "==================================" << endl;
for(char i = 0; i < 26 ; i++)
cout << pletters[i];
cout << endl;
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );


return 0;
}
Well if you just have to replace every other letter it's fairly simple, you could just make a simple for loop which iterates by two instead of one, and replace each letter in the corresponding position with an 'x'

PseudoCode

1
2
3
for (int var_name = 0; var_name < number_of_characters; var_name += 2)
replace pletters[var_name] with 'x'
print array


[code] Your code goes here [/code]
IIRC: char *pletters[] is an array of read-only c-strings. Use std::string if you want to modify them.
The idea is general: traverse the container and performs the action in the element if corresponds
Wow. Way to go. You didn't even use the `letters' array you created! You ought to just delete it and use pure C++ code rather than the stuff that Microsoft created. Oh, wait...you already are pretty much. ;)

--
Quick tutorial on character literals and string literals:

Character literals (type char) use single quotation marks such as 'A' and can only hold a single character.

A string literal such as "ABCDEFGHIJKLMNOPQRSTUVWXYZ" is known commonly as a C string, a NUL terminated string or occasionally an ASCIIZ string. It is actually an array of character literals: {'A', 'B', 'C', ..., 'Y', 'Z', '\0'}, where the '\0' at the end signifies the end of the string. The C programming language upon which C++ builds/improves has no real string type in the sense of other programming languages' definitions, only character arrays. Those character arrays are implicitly terminated with a '\0' character to create a C string.

C++ streams can output both character literals and string literals just fine:
1
2
cout << 'X' << endl;
cout << "ABCDEFG" << endl;
X
ABCDEFG

--

With that said, even if you must declare the letters individually, use character literals rather than string literals. It simplifies your problem a bit. Also since you aren't using your `letters' array<char>^ at all, you might as well drop the * and the 'p' on `pletters' and just use that as your `letters' array.

Lastly, if you are using i++ to do i = i + 1 in order to output each letter character-by-character, how would you use a similar loop to modify every other letter such as B, D, F, etc.?
String literals have the type: const char*.
Oh, wait a moment.

Each element consists of a letter and then a space. Does that mean that each one is a string...not a character?

For your question about the i++, would it be i = i + 2 to output every other letter?

I'm not certain I grasp the use of pointers quite yet, and ne555 has informed me that char* pletters[] is read-only.

I'm sorry, but I also forgot to mention that the output of this specific program must be this:

1
2
PRINTING CONTENTS OF ARRAY and adding x to every other element
A x C x E x G x I x K x M x O x Q x S x U x W x Y x


and that the code must update every other letter.

I already thought of just changing the array to exactly that, but the instructions specify that the code must make the change (darnit!).
I am thinking that it might have something to do with Dynamic Memory Allocation. It is in the chapter for this assignment.
could you use std::string?It would make this assignment much more easier to solve
I must use an array or a pointer. The name of the assignment is "Using Arrays and Pointers." :)

So I tried this:

1
2
3
4
5
for(i = 0; i <= 26; i = i +2)
            {
                 count += 2;
                 pletters[i] = x;
             }


And then I printed the array. It worked. Do you think that is an all right solution?
I haven't seen your code, but I guess it is ok if your assignment didn't ask you using any dynamic allocation

about your code
1 : the range of pletters start from zero
2 : if you want to insert the 'x' at the second position, it should start from subscript "1" but not "0"
1
2
3
4
5
char pletters[26] = {A, , B, , C.......};
for(int i = 1; i < 26; i += 2) //iterate from 1 to 25
{
 
}
Can you use #include <cstring>? This is my crack at this. Its not very efficient.
1
2
3
4
5
char result[100] = "";
  char *letters = strdup("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  for (int i = 0; letters[i] != '\0'; ++i)
    if (i % 2) strcat(result, " x ");
    else strncat(result, &letters[i], 1);
Hey I have the same homework and I am stuck on this part...... here is my code so far Idk what to do next. ugh. Thanks for any help.

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

// Arrays and Pointers program for Assignment week 4

#include<iostream>
#include<iomanip>

using std::cin;
using std::cout;
using std::endl;
using std::setw;

	int main()
	{
		
		char* pletter2[]=  { "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z" };
		char* pphrase = "PRINTING CONTENTS OF THE ARRAY";
		char* pphrase2 = "==============================";
		char* pphrase3 = "PRINTING CONTENTS OF THE ARRAY and adding x to every other element";
		char* pphrase4 = "==================================================================";
		char* pphrase5 = "x";
		
		int number = 0;
		int i;
	    

		    cout<<endl;
			cout <<pphrase;
		    cout <<endl;
		    cout <<pphrase2;
			cout <<endl;

	     for(int i = 0; i < 26; i++)
		{
			
		    
			 cout <<pletter2[i];
			
		
		}
          
			cout <<endl;
			cout <<endl;
		    cout <<"Please enter a number between 1 and 26 that corresponds to a letter in the alphabet: "<<endl;
		    cout <<endl;
			cout <<"Example: The number 10 corresponds to the letter J."<<endl;
			cin >>number;

		 if ( number >=1 && number <=26)
		 {
			     cout <<"The number you selected is: "<<number<<endl;
		         cout <<"The letter that corresponds with that number is: "<<pletter2[number-1]<<endl;
		 }
		          else 
		 {
			         cout<<"There was an error with your input please try again"<<endl;
		 }
		 
		 
		 {	
			
			 
		 int j = 0;

         cout <<endl;
		 cout << pphrase3;
		 cout <<endl;
		 cout <<pphrase4;
		 cout <<endl;

			for(j = 1; j <= 26; j = j +2)
            {
              
			    pletter2[j] = pphrase5;
				   cout <<pletter2;
             }
			
	    
		    
			
			return 0;
		}
Last edited on
The program will only print the lower case x's instead of keeping all of the letters in the array. I know that I told the program to count every other letter after A and then it replaces the letters with "pphrase5" but I don't know how to make the output the entire array after the letters are replaced. Thanks.
can't you actually use the increment operator on chars??
1
2
char start[] = 'A';
start++; // this will increment to B etc etc 


this will make it easier and more concise to build that first array.

Also, arrays start at 0
so, if ( number >=0 && number <=26)

I would make another char* array[(26x2)]
maybe make a function that discriminates even numbers... with an exception of 0
1
2
3
4
5
6
if ((number == 0) || number % 2 == 0)
//... this is even
//add x to that element in the array
else
//... this is odd
//put the letter here... 
Last edited on
Why are the supposed char arrays you are making three times larger...

 
char * str[] = {"A","B"};


that's one pointer for the array and two more for each string = 3 pointers
and 4 chars 2 that you can see and the null terminator = 4 chars

why not just

 
char *str = "AB";


1 pointer, 2 chars you see, and the null terminator.

plus, you don't need to dump to another array, you can manipulate in place with ease. It's not like you are sorting, so using another array won't speed things up at all. You should only really need it, if you aren't supposed to change the data in the array...


- edit: alternately you can do this

 
char str[] = { 'A' , 'B' };


and keep track of size, so you don't even need the null char...

-- edit.. I said null pointer instead of null char
Last edited on
Battousai, in your code you have this
1
2
3
for(j = 1; j <= 26; j = j +2) {
   //..
}


which will work, because it won't hit 26, but you shouldn't put the <= 26 it should remain < 26 as the largest element on your array is 26-1, so if you change the code, you will be out of range... so an array of 5 will go from 0-4 and to iterate it the for loop would look like this if I want every other letter starting from 1:

1
2
3
4
5
6
7
8
9
10
11
12
char str[] = {'A','B','C','D','E'};
for(int j = 1; j < 5; j = j +2) {
  std::cout << str[j] << std::endl;
}
// not using that j for anything else


/*
// that should output
B
D
*/


Note: I created the j inline with the for loop (not in the for loop). This is good. It only creates it once and won't conflict with anything else. I would only really create it outside if I want to use it later for instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
char str[] = {'A','B','C','D','E'};
int j; // I'm going to use j after the for loop
for(j = 1; j < 5; j = j +2) {
  std::cout << str[j] << std::endl;
}
std::cout << "you stopped the loop at j=" << j << std::endl;

/*
// that should output
B
D
you stopped the loop at j=5
*/


This is why we use 'i' all the time. One, it's short for "iterator" and two, we don't use it for anything else. So you can just use them in for loops... just remember if you have a nested for, you will have to use something else:

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
char str[] = {'a','b','c','d','e'};

for( int i = 0; i < 5; ++i ) {
  std::cout << str[i] << std::endl;
}
/*
// that should output
a
b
c
d
e
*/

// 'i' doesn't exist anymore in this scope after that  last for loop, so I can reuse it without a prob

for( int i = 0; i < 5; ++i ) {
  std::cout << str[i];
  //  'i' does exist here, so lets use a new one to not create conflicts...
  for ( int j = i; j < 5; ++j ) { // this will upper case this letter and all after it
    std::cout << toupper(str[i]);
  }
  std::cout << std::endl;
}

/*
// that should output
aABCDE
bBCDE
cCDE
dDE
eE
*/



-- edit: it's important to note that

1
2
3
for ( int i = 0; i < 5; ++i ) {
  //..
}


is about the same as

1
2
3
4
5
6
7
{
  int i = 0;
  while (i < 5 ) {
    //..
    ++i;
  }
}


There are differences, one being using "continue" in the while loop won't iterate the 'i', but that's not the point... The point is that it's not the same as this:

1
2
3
4
5
  while ( i < 5 ) { // well, you'll probably get an error here anyway, because i doesn't exist
    int i = 0;
    //..
    ++i; // this will always be 0 going to 1, because i is recreated in each loop
  }
Last edited on
kash kow ken, you can't increment that, unless it's a pointer... but you wouldn't be incrementing a char, you'd be incrementing the pointer. I don't suggest you do that unless you fully understand what is happening with the pointer. Some would say you shouldn't do it at all.

It would not increment to 'B', but you could do this with the one element array you had:
1
2
3
char start[] = 'A';
start[0]++; // <-- I'm pretty sure start[0] is now a 'B' since they are all numbers anyway
// why don't you write the code and check... 


but if you have a one element array, you might as well just have char start = 'A';

-- edit: if you do that, then you can do start++; on the char itself

if ( number >=1 && number <=26)
that would be fine, because they are subtracting 1 from the number to make it 0-25...
this:
if ( number >=0 && number <=26)
is not good, because something will be out of range. If you subtract 1 you could have a -1, if you don't you'll have a 26, both of which are out of the range you want.

if ((number == 0) || number % 2 == 0)

can be shortened to if ( number % 2 == 0 )

because 0%2 == 0

Last edited on
It seems like the only output I will get from the for loops you have posted will be every other letter? I need the program to replace B,D,F etc with x's and still have the program output all the other letters in between.
Pages: 12