# Infinite Loop

Discussion in 'C' started by chemr2, Oct 26, 2009.

1. ### chemr2New Member

Joined:
Feb 16, 2009
Messages:
17
Likes Received:
0
Trophy Points:
0
I have taken c++ but it has been about a year ago. I am taking mechanics of materials now and need to solve a bending moment problem. I am trying to get values of Sigma when a is between 0 and 20mm in 2mm increments. I have wrote a little bit of code and need to figure out if this would the correct approach? Also why is this loop infinite?
I do not have a copy of my text anymore so any help would be appreciated.

The equation I am solving for is Sigma = MC / I
Remember I need 16 values for Sigma when a is varying.

Code:
```#include<iostream>
#include<cmath>
using namespace std;

int main()
{

double n,M,C,I,Sigma,b,h,a,x,i;

n = 2.66;
C = .020;
M = 1500;

for(a=0;a<=.020;a+.002)
{

Sigma = (1500 * .020)/ ((1/12)*(.060)*pow(.040-2*a,3));
cout<<Sigma<<endl;
};

system("pause");
return 0;

}

```

2. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,012
Likes Received:
203
Trophy Points:
63
Occupation:
Senior Support Engineer
Location:
England
The loop does not modify a. Look carefully at the 3rd clause in the for statement.

3. ### chemr2New Member

Joined:
Feb 16, 2009
Messages:
17
Likes Received:
0
Trophy Points:
0
So a+.002 should be what I have listed below in red? If this is the case. I am still getting garbage answers.

Code:
```
#include<iostream>
#include<cmath>
using namespace std;

int main()
{

double n,M,C,I,Sigma,b,h,a,x,i;

n = 2.66;
C = .020;
M = 1500;

for(a=0;a<=.020;[B][COLOR=red]a+=.002[/COLOR][/B])
{

Sigma = (1500 * .020)/ ((1/12)*(.060)*pow(.040-2*a,3));
cout<<Sigma<<endl;
};

system("pause");
return 0;

}
```

4. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,012
Likes Received:
203
Trophy Points:
63
Occupation:
Senior Support Engineer
Location:
England
What answers do you get and what answers do you expect?
Do you get different answers if you add ".0" to the end of each integer in the expression?
Code:
```Sigma = (1500.0 * .020)/ ((1.0/12.0)*(.060)*pow(.040-2.0*a,3.0));
```

5. ### SaswatPadhi~ Б0ЯИ Τ0 С0δЭ ~

Joined:
May 5, 2009
Messages:
1,343
Likes Received:
55
Trophy Points:
0
Occupation:
STUDENT !
Location:
Orissa, INDIA
Home Page:
Probably, he was getting all values as "Infinity".

@chemr2 :
The problem is because of the 1/12 in the denominator.

Both 1 and 12 are integers. Change at least one of them to float to get proper results.
This should be sufficient :
Code:
`Sigma = (1500.0 * .020)/ ((1.0/12)*(.060)*pow(.040-2.0*a,3));`
BTW, this is NOT what we call an infinite loop.
Your loop is finite, but the output values are infinite