# Thread: Executing For Loop

1. ## Executing For Loop

Code:
```// program asks user to enter a number
//the program then prints how many digits user entered.
//code works.
//what I don't understand is how the for loop works.
//can someone explain each step the for loop takes up until it prints out the answer. thx

#include <stdio.h>
int main(void)

{

int n,i,x;

printf("Please enter a positive integer: ");
scanf("%d",&n);
x=n;   //dummy variable

for ( i=0; n>0; i++) //for loop
{  n=n/10;  } 	//reduces the number "n"

printf("Number %d is %d digits long.\n",x,i);

return(0);
}```

2. BE the loop... Sit down with a pencil and paper, write down the value of each variable for each time through the loop... exit when the exit condition is met...

You'll figure it out...

(And yes, that's how the big guns do it.)

3. If i enter number 17.
n=17/10=1.7 which satisfies the for loop
so therefore (i=1; n>0;i++)
does the for loop execute again? or does it stop there.
because int n is declared as an integer does the answer 1.7 round to 2? or does it round down to 1?

4. Originally Posted by mshel130
If i enter number 17.
n=17/10=1.7 which satisfies the for loop
so therefore (i=1; n>0;i++)
does the for loop execute again? or does it stop there.
because int n is declared as an integer does the answer 1.7 round to 2? or does it round down to 1?
You have integer division. So what you actually have is:

n = 17
n / 10 = 1

Integer division does not round, it truncates.

Quzah.

5. Put a printf statement in the loop that outputs the values of n and i. Then you can see what those values are and how they change each iteration of the loop. That should help you understand what is going on.

Popular pages Recent additions