Sunday, August 2, 2009

Explain me this clearly? C++ code.?

#include %26lt;iostream%26gt;


using namespace std;


#define MAX 20





main(void)


{


int loop;


int hold[MAX];


int counter = 0;


char more;





while(1){


cout %26lt;%26lt; "enter a num" ;


cin %26gt;%26gt; hold[counter]; \\explain me this. Why was counter but in an array form[] ********************


cout %26lt;%26lt; "\nENTER MORE NUM (Y,N)";


cin %26gt;%26gt; more;


if(more == 'n'){


break;


}else{


counter++;


}





}


for(loop = 0; loop %26lt;= counter; loop++){


cout %26lt;%26lt; "element in" %26lt;%26lt; counter+1 %26lt;%26lt; " is " %26lt;%26lt; hold[loop]; \\ why was loop in a array[] in hold.


}


system("PAUSE");


return(0);





}

Explain me this clearly? C++ code.?
cin %26gt;%26gt; hold[counter]; \\explain me this. Why was counter but in an array form[]





this is assigning the stuff you are typing into the hold array variable at the index of "counter" (which is incrementing each time the while loop iterates)





2. cout %26lt;%26lt; "element in" %26lt;%26lt; counter+1 %26lt;%26lt; " is " %26lt;%26lt; hold[loop]; \\why was loop put in a array form inside hold.





this is outputting the hold array at the index of "loop" while the for loop increments loop until loop is less than or equal to the counter you generated in the while loop.





the while loop iterates until you Type N. As it loops it keeps incrementing "counter" up and indexing the hold array by "counter" for your input to be stored in...





hold[0] = "your input here"


hold[1] = "your second input here"





then the for loop takes the counter and uses it as it's maximum and loops using "loop" as the iterator and as the index for the hold array.





printing out "your input here"


then "your second input here"











make sense?
Reply:this program accepts integer in an array hold which can hold maximum of 20 elements. counter is used as index which is incremented each time when there are more elements to enter. when finished the loop exits. the next for loop is used to display the elements entered. Always the arrays are used with there indexes which shows the elements offset. hold[0],hold[1]....hold[20] are the elements if array hold.
Reply:Someone else has already explained the code.





What I would consider more appropriate for C++:





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


#include %26lt;vector%26gt;


using namespace std;





int main()


{





vector%26lt;int%26gt; nums;


string answer = "y";


int number = 0;


while(answer == "y")


{


cout %26lt;%26lt; "Enter a number".


cin %26gt;%26gt; number; nums.push_back(number);


cout %26lt;%26lt; "Another number (y/n) ?"


cin %26gt;%26gt; answer;


}





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


{


cout %26lt;%26lt; "Element in " %26lt;%26lt; i %26lt;%26lt; " is " %26lt;%26lt; nums[i] %26lt;%26lt; endl;


}





return 0;





}

nobile

No comments:

Post a Comment