0
Why this code don't work?
4 Réponses
+ 4
Julianna you must get the input N times, so put the input inside the loop.
There is no need to use an array for input. Each input value is used only once. You can re-use the same variable for input the next time through the loop.
The break statement is breaking your code. It causes the loop to exit upon finding the first odd number. Let the loop finish examining all N numbers by removing the break.
Suggested improvements:
#include <iostream>
using namespace std;
int main() {
int N;
int count=0;
cin>>N;
int n;
for (int i=0;i<N;i++){
cin>>n;
if(n%2==0){
count=count+n;
}
}
cout<<count;
}
+ 3
Julianna
You have to take N number of input inside loop and don't use break in else part inside loop otherwise loop execution will stop after 1st or 2nd iteration
//cin>>n[N];
for (int i = 0; i < N; i++) {
cin >> n[i];
if(n[i] % 2 == 0) {
count = count + n[i];
}
}
+ 3
+ 2
#include <iostream>
using namespace std;
int main() {
int N;
int count=0;
cin>>N;
for (int i=0;i<N;i++){
if(i%2==0){
count=count+1;
}
}
cout<<count;
}