Reputation:
I'm a very beginner. I'm trying to solve some problems and being stuck right at the first one. The while loop runs but then I try using for loop and it never runs
#include <iostream>
using namespace std;
int main(){
int n=910;
int digits_sum=0;
for(int i=n;i=0;i/=10)
digits_sum+=(i%10);
cout<<digits_sum;
return 0;}
I googled and found on codescrackers:
int num, rem, sum;
cout<<"Enter the Number: ";
cin>>num;
for(sum=0; num>0; num=num/10)
{
rem = num%10;
sum = sum+rem;
}
cout<<"\nSum of Digits = "<<sum;
The code runs and it gives me other questions:
It seems I still don't get the for
loop statement fully so this is how it runs with my understanding:
init value i = n = 910
condition to be out of the loop: i = 0
decrement: i = 910/10 = 91
Could you please tell me where did I go wrong?
Upvotes: 0
Views: 8722
Reputation: 11340
To quoute from your question:
condition to be out of loop: i=0
You have two misunderstandings here:
i = 0
is an assignment, you want a comparison i == 0
So the only thing you have to do is to change
for(int i=n;i=0;i/=10)
to
for(int i = n; i != 0; i /= 10) // loop as long as i does not equal 0
Upvotes: 3