user11822694
user11822694

Reputation:

C++ for loop to find "sum of digits of a given number"

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:

  1. why is the init value sum=0?
  2. Why is condition num>0

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

Answers (1)

Lukas-T
Lukas-T

Reputation: 11340

To quoute from your question:

condition to be out of loop: i=0

You have two misunderstandings here:

  1. i = 0 is an assignment, you want a comparison i == 0
  2. It looks you interpreted this as "exit if this is condition is fullfilled", but in fact the opposite happens: The loop will continue as long as this condition is true.

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

Related Questions