Reputation: 3
I am a new student in a programming fundamentals course. I have absolutely no previous experience with programming. I am trying to understand a question that was posed on a recent quiz about arrays. This is it: What will be the output of the pseudocode below?
nums = [30, 10, 20, 50, 40]
val = 0
For i = 0 to 5
val = nums[i] + val
Display val
Thanks for any thoughts on this. I don't understand it at all. I originally thought 40 was the answer but sadly, that was wrong lol. Can someone tell me what the answer is and explain why that's so? Our textbook doesn't have any examples like this.
Upvotes: 0
Views: 984
Reputation: 107989
As posed, the correct answer is "This code generates an error/exception." The reason is that the loop is iterating over six array elements, but the array contains only five. Here are just some of the things that various real languages might do in this case:
But the one thing you can be sure of is that the program is incorrect.
Upvotes: 1
Reputation: 221
Well, as Wayne already said, the for loops is running on to many times, which would result in an exception. Assuming that is a mistake and that the loop only runs 5 times. Then your result would be 30 + 10 + 20 + 50 + 40, as it just adds all values of the array up and saves it in val
. So it would probably display 150, unless I am completely wrong and I also misunderstood it.
Upvotes: 1