- 3

why my commented (//....) code is not working?

#include<iostream> using namespace std; int main(){ // int sum=0; // cout<<"Enter number"<<endl; // cin>>k; // for(int i=0; 1<i<=9;i++){ // if(i%2==0){ // sum=sum+i; // } // else{ // return 0; // } // //cout<<sum; // } //} int sum=0, k; cout<<"enter number"; cin>>k; for(int i = 0; i <= k; i++) if(i % 2 == 0) sum += i; cout << sum << endl; }

27th Mar 2021, 3:54 AM
Adeeba
Adeeba - avatar
6 Respuestas
+ 3
♨ Soumik 🎶 Yes maybe but if she can add more details like what she is doing here so we can tell.
27th Mar 2021, 5:40 AM
A͢J
A͢J - avatar
+ 2
Because when you consider a line of code as a comment, compiler ignores that line while running.
27th Mar 2021, 4:55 AM
Zahra ツ
Zahra ツ - avatar
+ 1
Adeeba Comments are used for understanding purpose means anyone can understand easily what is going on in the code. Compiler ignore comments to execute.
27th Mar 2021, 5:15 AM
A͢J
A͢J - avatar
0
🅘🅜 🅰🅹 !!! Zahra ツ The question meant to say why the code will not work if the comments were to be removed.
27th Mar 2021, 5:29 AM
Soumik
Soumik - avatar
0
First Problem: int sum=0; ... cin>>k; => there ist no k. sum ist the only variable you declared. Second Problem: for(int i=0; 1<i<=9;i++) Here is an explanation what happens in this code: "1 < i <= 9" translates to (1< i) <= 9, which results in either 0 <= 9 or 1 <= 9 (depending on i) And this expression is always true. You basically create an infinite loop. And here is a description of how to achieve what you want: To express "a < b < c" you need to split it up into "a<b" and "b<c". Combine these with a logical 'and' operator (a < b && b<c).
27th Mar 2021, 11:44 AM
Alex
Alex - avatar