MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Solved

Posted on 2003-10-31

please explain to me how this for statement works:

assuming that stack is a class with stack type set to int and stack capacity to 5. Give the content of myTop and myArray data memebers of s after code segment has been executed.

Stack s;

for (int i = 0; i<5; i++) //please help me in this step, what is the first value of i

s.push(2*i); //what are the values of all the i's please help me.

s.pop();

s.pop();

the answer according to my professor is myTop = 2 and myArray is 0, 2, 4, 6 but please help me understand why it is so. i had this question on an exam and i need to understand it.

assuming that stack is a class with stack type set to int and stack capacity to 5. Give the content of myTop and myArray data memebers of s after code segment has been executed.

Stack s;

for (int i = 0; i<5; i++) //please help me in this step, what is the first value of i

s.push(2*i); //what are the values of all the i's please help me.

s.pop();

s.pop();

the answer according to my professor is myTop = 2 and myArray is 0, 2, 4, 6 but please help me understand why it is so. i had this question on an exam and i need to understand it.

1 Comment

set an integer 'i' equal to 0. while 'i' is less than 5 run the corresponding body, and add 1 to 'i' after each iteration through the loop.

So basically the for loop in your example runs 5 times. The first time i is equal to 0, then 1, then 2, until it reaches 4. When i is equal to 5 it wont run because the condition in the for loop says to run while i<5.

since you are pushing 2*i onto the stack, you will basically push the values 0, 2, 4, 6, 8. Then the last two commands will pop 8, and 6 from the stack.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Title | # Comments | Views | Activity |
---|---|---|---|

How to programmatically differentiate between C and Java | 10 | 204 | |

Header Errors LNK2019, LNK1120 - Unresolved Externals | 4 | 194 | |

How do i run a c++ file? | 15 | 46 | |

How to determine if the result of an equation is an integer in C++? | 3 | 19 |

The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

Join the community of 500,000 technology professionals and ask your questions.