What will be the output of the following code snippet?void solve() { int a[] = {1, 2, 3, 4, 5}; int sum = 0; for(int i = 0; i < 5; i++) { if(i % 2 == 0) { sum += a[i]; } } cout << sum << endl;}
Question
What will be the output of the following code snippet?void solve() { int a[] = {1, 2, 3, 4, 5}; int sum = 0; for(int i = 0; i < 5; i++) { if(i % 2 == 0) { sum += a[i]; } } cout << sum << endl;}
Solution
The output of the code will be 9.
Here's the step-by-step explanation:
- An integer array
ais declared and initialized with the values {1, 2, 3, 4, 5}. - An integer
sumis declared and initialized with the value 0. - A for loop is started which runs from
i = 0toi = 4. - Inside the loop, there is an if condition that checks if
iis even (i % 2 == 0). Ifiis even, the value ofa[i]is added tosum. - For
i = 0,a[i]is 1, so 1 is added tosum. - For
i = 1,iis not even, so nothing is added tosum. - For
i = 2,a[i]is 3, so 3 is added tosum. - For
i = 3,iis not even, so nothing is added tosum. - For
i = 4,a[i]is 5, so 5 is added tosum. - After the loop,
sumis printed. The value ofsumis 1 + 3 + 5 = 9. So, 9 is printed.
Similar Questions
What is the output of the following code?#include <iostream>using namespace std;int main() { int a[] = {5,1,15,20,25}; int i, j, k; i = ++a[1]; j = a[1]++; k = a[i++]; cout << i << " " << j << " " << k; return 0;}Options: Pick one correct answer from below3 2 152 3 202 1 151 2 20
What is the final output of the following code?int a = 5;int b = 10;int c = 3;for(int x =0; x< 5; x++){ a += 2; b -= 1; c *= 2;}cout<<"A is "<<a<<" and C is "<<c<<endl
What is the output of the following code?#include <iostream>using namespace std;int main() { int a[]={5,6,7,8}; cout << * (a + 2) << " " << a[1]; return 0;}Options: Pick one correct answer from below8 67 66 65 7
What will be the output of the following code?int i = 1;while(i<10){ if (i % 2 == 0) cout << i << “ ”; i++;}
What is the output of the following snippet? #include <iostream> using namespace std; int main(){ int i = 2; if (i--==1) cout << i; else cout << i + 1; return 0; } i + 1 2 3 1
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.