15,904,023 members
See more:
The question is:

Rewrite the following program segment with a for loop:

C++
```count = 0;
i = 0;
while (i < n) {
scanf("%d", &X);
if (X == i)
++count;
++i;
}```

Please help me. If you would, please write out the code and explain why. I know how to write a for loop; however, because of how this code is set up, I am confused and in need of help. Please do not use any C++ language that I would not know since I am only in a Programming Fundamentals class and I am only currently learning C.
Posted
Updated 27-Oct-15 17:41pm
v2
[no name] 28-Oct-15 0:05am
You want the answer AND explanation without making any attempt yourself? If that's too hard what about Google?
Member 12092855 28-Oct-15 12:19pm
I did make an attempt. But I'm not sure if I'm correct. I wanted an explanation because I want to understand it.
Matt T Heffron 28-Oct-15 13:36pm
SO show us what you tried.
If it doesn't work, tell us what it does wrong.
But we WILL NOT just DO IT for you!
[no name] 28-Oct-15 20:55pm
MTH has said it all.
Krunal Rohit 28-Oct-15 0:51am

count = 0;
i = 0;
for(i=0; i<n; ++i)="" {="" scanf("%d",="" &x);="" if="" (x="=" i)="" ++count;="" }="" &nbsp;="" <="" b="">
[Format didn't apply, hence deleted]
-KR

## Solution 1

It is actually very simple and you only need to read up on how a for loop and a while loop works. It is better not to give you an answer, but to give you some pointers instead.

for loop in C[^]

while loop in C[^]

Lesson 3: Loops[^]

You should also learn and understand the difference between the execution of ++i and i++.

## Solution 2

Thank you everyone for the help. I simply misread the code. The answer is

C#
```count = 0;

for (i = 0; i < n; ++i);
{
scanf("%d", &X);
if (X == i)
{
++count;
}
}```

For some reason the if statement didn't resonate in my head that it was there, so I over complicated the problem. But thank you everyone for your input.