for statement not being executed but while statement works..

I am using code block ide. I am trying to write a program that calculates parallel resistor value. I have the program so far set up for the person to enter the number of resistors in parallel. I then wanted to use a for statement to have the person enter all the resistor values and I would store them in a array.
When I run the following code it compiles fine but only prints the first cout and cin, then exits. It skips my for statement.

#include <iostream>
//m

int main()
{
using std::cin;
using std::cout;

int numOfResistors;
int loopMax;
int loopCount;

cout << "How many resistors in parallel:";
cin >> numOfResistors;
cout << numOfResistors;

loopMax = numOfResistors;
float resistorValues[numOfResistors];

for (loopCount=0;loopMax==loopCount; ++loopCount){
cout << "Value of resistor:";
cin >> resistorValues[loopCount] ;
}

return (0);
}


I have changed the loopcount = 1 ect and I have wrote the program 3 other ways with minor changes with the same problem.
I can get it to work with a while statement as follows...



#include <iostream>



int main()
{
using std::cin;
using std::cout;

int numOfResistors;
int maxResistors;
int loopCount=1;


cout << "How many parallel resistors:";
cin >>numOfResistors;

maxResistors = numOfResistors;
float resistorValue[numOfResistors];
while (maxResistors >= loopCount){
cout <<loopCount<<" resistor value in Ohms:" ;
cin >> resistorValue[loopCount];
++loopCount;
}
return 0;
}



Was wanting to use the for statement but it is just not working. Any help would be appreciated.
Well, it should be -> for (loopCount=0; loopMax > loopCount; ++loopCount) // > instead of ==
Last edited on
Ok, I changed it to loopMax>loopCount and it worked, but I do not understand why i needed to . Would the loop not run unitl loopmax==loopCount, or would it not initiate the loop until loopmax==loopCount... Any guidance for further understanding would be helpful.
Last edited on
The reason it wouldn't stop is because you never modified those variables within the loop. That comparison will always be true.
http://cplusplus.com/doc/tutorial/control/

The condition you supply in the for loop must be satisfied for the "for" loop to continue.
It runs until the condition is not met, which in your case was the first iteration.
teclordphrack2 wrote:
would it not initiate the loop until loopmax==loopCount

No. It will initiate the loop while loopmax == loopCount

A for loop is just a while loop in disguise.

1
2
3
4
5
6
7
8
9
10
11
12
for( int i = 0; i < N; ++i ) {
   //body
}
//--------------------------------------------------
//is the same as
{
  int i = 0;
  while( i < N ) {
    //body
    ++i;
  }
}
Topic archived. No new replies allowed.