What is the output for the following code?123456789101112131415#include <stdio.h> int main() { int n = 5; int arr[5] = {1, 2, 3, 4, 5}; int e = 0; for (int i = 0; i < n; ++i) { if (arr[i] % 2 == 0) { ++e; } } double p = (double)e / n * 100; printf("%.2f", p); return 0;}
Question
What is the output for the following code?123456789101112131415#include <stdio.h> int main() { int n = 5; int arr[5] = {1, 2, 3, 4, 5}; int e = 0; for (int i = 0; i < n; ++i) { if (arr[i] % 2 == 0) { ++e; } } double p = (double)e / n * 100; printf("%.2f", p); return 0;}
Solution
The output of the code will be 40.00.
Here's the step-by-step explanation:
-
The code declares an integer array
arrof size 5 and initializes it with the values 1, 2, 3, 4, 5. -
It also declares an integer
eand initializes it to 0. This variable is used to count the number of even numbers in the array. -
The
forloop iterates over each element in the array. For each element, it checks if the element is even by using the modulus operator (%). If the element is even (i.e.,arr[i] % 2 == 0is true), it increments the countere. -
After the loop, the code calculates the percentage of even numbers in the array. It does this by dividing the number of even numbers (
e) by the total number of elements in the array (n), and then multiplying the result by 100. The result is cast to adoubleto allow for decimal precision. -
Finally, the code prints the percentage with a precision of two decimal places. Since there are 2 even numbers (2 and 4) out of 5 total numbers in the array, the output is 40.00.
Similar Questions
What is the output for the following code?
What will be the output of the following program?1234567891011121314151617181920#include <stdio.h>void one();void two();void one() { for(int i = 0; i < 2; i++){ two(); }}void two() { printf("TWO ");}int main(){ one(); two(); return 0;}
What is the output for the following code?12345678910111213#include <stdio.h> int main() { int i = 1; while (i <= 10) { if (i % 5 == 0) { i++; continue; } printf("%d ", i); i++; } return 0; }
What is the output for the following code?123456789#include <stdio.h>int main(){ char ch = '1'; for (ch = '5'; ch <= '8'; ch++) putchar(ch); return (0);}
What will be the output of the following code snippet?123456789101112131415#include <stdio.h> int main() { char direction = 'N'; if (direction == 'N') printf("North"); else if (direction == 'S') printf("South"); else if (direction == 'E') printf("East"); else if (direction == 'W') printf("West"); else printf("Unknown"); return 0; }
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.