Click here to Skip to main content
15,888,013 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I am creating a program that will display a table with the length and the period of a pendulum. I ask the user for a length and then for an updated/2nd length. I use a for loop to keep displaying the table values. I am allowed to display up to 20 lines at most. I keep getting an infinite loop when I run it. Please help. P.s I am required to create the function and the user can also enter a negative value for the 2nd length, for example -2. Thank you for the help.

What I have tried:

C++
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.141592

    double pendulum_Period(double length);
int main()
{
    double length;
    double updateLength;
    int i;



    printf("\nThis program displays a table of Pendulum lengths and their respective period.\n"
           "\nPlease enter the length of the pendulum(ft):  ");
    scanf("%lf", &length);

    if( length <= 0 )
    {
        printf("\n\nError: Length must be > 0\n"
               "Please enter the length of the pendulum(ft):   ");
        scanf("%lf", &length);
    }


    printf("\n\nPlease enter the update value for the length(ft):  ");
    scanf("%lf", &updateLength);



     printf("\nLength(ft)\t\t\tPeriod(s)\n"
            "------------------------------------------\n");


    for( i = length; i <= 20; length += updateLength)
    {
        double period = pendulum_Period(length);
        printf("%.6f\t\t\t%.6f\n", length, period);
        printf("------------------------------------------\n");
    }


    return 0;
}


    double pendulum_Period(double length)
    {

        double T;
        double period;
        double gravity;
        gravity = 32.2;
        T = (2 * PI)*(sqrt(length/gravity));
        period = T;

        return period;
    }
Posted
Updated 2-Apr-20 15:51pm
v2

Take a look at this loop:
C++
for( i = length; i <= 20; length += updateLength)
{
    double period = pendulum_Period(length);
    printf("%.6f\t\t\t%.6f\n", length, period);
    printf("------------------------------------------\n");
}

Now what happens if you change the first printf to
C++
printf("loop %d: %.6f\t\t\t%.6f\n", i, length, period);

That should help you figure out why the loop continues infinitely.
 
Share this answer
 
Comments
CPallini 3-Apr-20 2:17am    
5.
You forgot to increment i counter. Your

for( i = length; i <= 20; length += updateLength)


most likely should be

for( i = length; i <= 20; i += updateLength)
 
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