Help with Practice Exam Problem - (Arrays)

Hi folks,

I'm preparing for my final C++ exam by completing some practice exam problems, and this particular problem has me stumped.

The output is "7." If someone could please explain (step-by-step) how I can calculate the output to get 7 I would appreciate it.

Here's the problem:

1
2
3
4
5
6
7
8
9
10
int arr[5] = {2, 6, 5, 7, 9};
int s = 0;
for (int c = 0; c < 5; c = c + 1)
{
    if (arr[c] < 6)
    {
        s = s + arr[c];
    }
}
cout << s << endl;


What is the output?

Answer

A. 0


B. 2


C. 7


D. 29



So the for loop goes through the array element-by-element.

The if statement checks the current element and sees if it is less than 6, if it is it adds it to the sum.

The only elements less than 6 are 2 and 5.

So it will be 2 + 5 = 7
Last edited on
Thank you!

So am I to assume that s = s + arr[c]

should be calculated as s = 2 + 5

making s = 7?
Yeah whenever the current element is 5, it will be calculated as s = 2 + 5;
And every element after 5 is 6 or greater so nothing else will be added to the sum.
You have an array with five elements, hence why you're for-looping through it five times. The variable s starts at the value of 0.

Inside your loop, all you're doing is seeing if the value stored in the index you're at (so index 0 would be the value 2, index 1 would be the value 6) is less than 6 or not. The phrase s = s + arr[c]; (or s += arr[c]; means that it's going to add the value of the current index to variable s if that number meets the conditions of the if statement.

So knowing this, all you have to do is check that condition against the values in your array. Only two of the numbers are less than 6.

EDIT: Too slow!
Last edited on
lol well your answer was quite a bit more detailed than mine.
1
2
3
4
5
6
7
8
9
10
int arr[5] = {2, 6, 5, 7, 9};  // An array of integers (some of the numbers in it are LESS THAN 6)
int s = 0;  // Declare a variable to hold a SUM and initialize it to 0
for (int c = 0; c < 5; c = c + 1)  //  Start a loop that counts from 0 to 5
{
    if (arr[c] < 6) //  If the number in the array at index c is LESS THAN 6...
    {
        s = s + arr[c]; // ADD that number to the current SUM
    }
}
cout << s << endl; //  Print the SUM  


Basically the array elements are checked one at a time. If any element is less than 6 it gets added to the sum. Since only two elements are less than 6 (2 and 5), you get a total of 7.

The best way to understand this type of question is to get a piece of paper and pretend you are the compiler. Work through the program stepping through the loop and updating your values on the paper.
LOL! You guys are awesome! Thanks so much for all the detail.

It matters to a "newbie" like me. :-)
Topic archived. No new replies allowed.