Help me out here please! | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 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?

26th Jan 2018, 6:58 AM
Eeshan Gaonkar
Eeshan Gaonkar - avatar
6 Réponses
+ 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
26th Jan 2018, 7:13 AM
‎ ‏‏‎Anonymous Guy
+ 2
worked! thanks for all your help Vlad serbu & Brent!
26th Jan 2018, 7:12 AM
Eeshan Gaonkar
Eeshan Gaonkar - avatar
+ 1
The while causes an infinite loop. You may want to use if(i%3==0).
26th Jan 2018, 7:05 AM
Vlad Serbu
Vlad Serbu - avatar
+ 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
26th Jan 2018, 7:09 AM
Eeshan Gaonkar
Eeshan Gaonkar - avatar
+ 1
but could someone explain to me once how the while loop did not work?
26th Jan 2018, 7:13 AM
Eeshan Gaonkar
Eeshan Gaonkar - avatar
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.
26th Jan 2018, 7:10 AM
Vlad Serbu
Vlad Serbu - avatar