+ 2
Help me out here please!
#include <iostream> using namespace std; int main() { int i,n,temp,sum; cin>>n; for(i=0;i<n;i++) { while((i%3)==0) { temp=i; sum=sum+temp; } } cout<<sum; return 0; } ------------------------------------------------- can someone please tell me why i keep getting a "time limited exceeded" error here? is this type of data structure usage time consuming?
8 Respuestas
+ 3
in your while loop there is no terminating statement or conditions. When i%3 becomes 0, it stays true forever. so you created an infinity loop here.
just add a break statement at the end of while loop and everything will work properly
+ 2
worked! thanks for all your help Vlad serbu & Brent!
+ 1
The while causes an infinite loop. You may want to use if(i%3==0).
+ 1
just tried the if loop...however I'm getting an garbage value...I'd like to print of the sum of multiples of 3 for a given number.
ex- 10-3,6,9
+ 1
but could someone explain to me once how the while loop did not work?
0
@Eeshan that's because sum doesn't have an initial value so it just gets what used to be at that memory location. Use sum=0 in the first line after main to initialize it with 0.