C++ issues | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

C++ issues

You want to take a list of numbers and find the sum of all of the even numbers in the list. Ignore any odd numbers. Task: Find the sum of all even integers in a list of numbers. Input Format: The first input denotes the length of the list (N). The next N lines contain the list elements as integers. Output Format: An integer that represents the sum of only the even numbers in the list. Sample Input: 9 1 2 3 4 5 6 7 8 9 Sample Output: 20

20th Feb 2024, 2:55 PM
Solo Ams
Solo Ams - avatar
8 Respuestas
+ 1
Hi Solo Ams If you are facing any issue show us your attempt by attaching your code.
20th Feb 2024, 4:00 PM
ūĚėēūĚėČ
ūĚėēūĚėČ - avatar
+ 3
Use for loop and check if number is even (i % 2 == 0) and then add in a variable called sum.
20th Feb 2024, 4:23 PM
AÕĘJ
AÕĘJ - avatar
+ 3
In the first for loop you are not taking user input it is just printing nos from 1 to n. In the second for loop you are adding even value of loop variable "i" not the even numbers of all the numbers entered by user
20th Feb 2024, 5:21 PM
ūĚėēūĚėČ
ūĚėēūĚėČ - avatar
+ 2
Hi Solo Ams Inside the first for loop in order to take user inputs you have to use "cin" not "cout" And in the same loop only you can add condition to filter even nos and add it to "even" variable like below for (int i = 0; i < n; i++) { int num; cin >> num; if (num % 2 == 0) { // Add even nos to the even even += num; } } And also remove below printing statements or make it comment when executing the code and print only "even" variable at the end as input and output format should match. cout << "Enter List size" << endl; cout << "These are all the integers in the list size" << endl; cout << "The sum of the even numbers from 1 - " << n << " is: " << even << endl;
20th Feb 2024, 5:36 PM
ūĚėēūĚėČ
ūĚėēūĚėČ - avatar
+ 1
//C++ #include<iostream> using namespace std; int main() { // Program to out the sum of even numbers in a range of number int n; int even = 0; cout << "Enter List size" << endl; cin >> n; cout << "These are all the integers in the list size" << endl; for (int i = 1; i <= n; i++) { cout << i << endl; } for (int i = 0; i <= n; i = i + 2) { even += i; } cout << "The sum of the even numbers from 1 - " << n << " is: " << even << endl; return 0; }
20th Feb 2024, 5:08 PM
Solo Ams
Solo Ams - avatar
0
Hello NB‚Äé Find my code above pls AÕĘJ I actually did use the for loop
20th Feb 2024, 5:17 PM
Solo Ams
Solo Ams - avatar
0
The first for loop generates the list of values from input of the user. The second for loop add up only the even numbers from the list generated and gives the sum
20th Feb 2024, 5:26 PM
Solo Ams
Solo Ams - avatar
0
Write a program to find area and circumference of circle
22nd Feb 2024, 2:51 PM
tej bahadur singjali
tej bahadur singjali - avatar