Sunday, July 12, 2009

Help with array in c++?

Hey im doing this program and i really need some help.





The program is to store alphabet as characters in an array


it must also:


Print the alphabet


Print the first 6 characters


the last ten characters


and the tenth character





Here is what i done so far








#include%26lt;iostream.h%26gt;





int main()


{





char alpha[27]={'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','\0'};





cout %26lt;%26lt; "The alaphabet is\n"%26lt;%26lt; alpha %26lt;%26lt;endl;








return 0;


}





The code above only prints the alphabet i think i should use something call pointers or summin to output the other characters but i don't know how

Help with array in c++?
You've done a good job so far, now it's just a matter of calling the right characters to print.





You will want to do a print statement something along these lines:





Print the first 6 characters:


int k;


for (k =0; k %26lt; 6; k++)


{


cout %26lt;%26lt; "The first 6 characters are\n"%26lt;%26lt; alpha[k]%26lt;%26lt;endl;


}








Print the last 10 characters:


int j;


for (k=27; k%26gt;=18; k --)


{


cout %26lt;%26lt; "The last 10 characters are\n" %26lt;%26lt; alpha [k]%26lt;%26lt;endl;


}





Print the 10th character:


cout %26lt;%26lt; "The 10th character is: " %26lt;%26lt; alpha[9]%26lt;%26lt;endl;








You might need to change the syntax up a little bit but this should give you general information and help about how to set up these simple print statements.





I hope this helps


Best Wishes
Reply:You need to loop through every value in the array.





cout %26lt;%26lt; "The alphabet is\n";





for(int i= 0; i %26lt; 26; i++)


{


cout %26lt;%26lt; alpha[i] %26lt;%26lt; endl;


}
Reply:You don't need pointers for this particular exercise.


//first 6


for(int i=0;i%26lt;6;i++)


cout %26lt;%26lt; "Letter " %26lt;%26lt; (i+1) %26lt;%26lt; " is " %26lt;%26lt; alpha[i] %26lt;%26lt; endl;


//last 10


for(int i=15;i%26lt;26;i++)


cout %26lt;%26lt; "Letter " %26lt;%26lt; (i+1) %26lt;%26lt; " is " %26lt;%26lt; alpha[i] %26lt;%26lt; endl;


//10th


cout %26lt;%26lt; "The 10th Letter is " %26lt;%26lt; alpha[9] %26lt;%26lt; endl;
Reply:why dont you use for loop?


If you wanna print t, u,w,x,y,z then a for loop that counts 6 elements from the index of element you want to print, and then just print inside the for loop.


something like this:


for(counter = 22;counter%26lt;28;counter++)


{


cout%26lt;%26lt;alpha[counter] + "\n";


}


this prints from the index 22 to 28 in different lines. and you know how to change it so it prints in oneline.


hope it helped and good luck


No comments:

Post a Comment