Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (6 votes)
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
Comments
[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.
We can help you to understand where your "thinking may be 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

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++.
 
Share this answer
 
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900