Nora
Nora

Reputation: 11

How do i convert a while loop to a for loop in C++?

while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}

Above is the while loop I had for my original program and below is my attempt at converting that to a for loop.

for (counter = 0; counter < total; counter++)
{
    inFile >> grade;        
    cout << "The value read is " << grade << endl;
    total = total + grade;  
}

This is a simple program to get grade averages. Here is the entire program:

#include <iostream>
#include <fstream>
using namespace std;
int average (int a, int b);
int main()
{
// Declare variable inFile
    ifstream inFile;
// Declare variables
    int grade, counter, total;
// Declare and initialize sum
    int sum = 0;
// Open file 
    inFile.open("input9.txt");
// Check if the file was opened
    if (!inFile)
    {
    cout << "Input file not found" << endl;
    return 1;
    }
// Prompt the user to enter the number of grades to process.
    cout << "Please enter the number of grades to process: " << endl << endl;
    cin >> total;
// Check if the value entered is outside the range (1…100).
    if (total < 1 || total > 100)
    {
        cout << "This number is out of range!" << endl;
        return 1;
    }
// Set counter to 0.
    counter = 0;
// While (counter is less than total)
    // Get the value from the file and store it in grade.
    // Accumulate its value in sum.
    // Increment the counter.
    while (counter < total)
    {
    inFile >> grade;
    sum += grade;
    counter++;
    }
// Print message followed by the value returned by the function average (sum,total).
    cout << "The average is: " << average(sum,total) << endl << endl;

    inFile.close();

    return 0;

}
int average(int a, int b)
{   

return static_cast <int> (a) /(static_cast <int> (b));
}

I tried to convert while loop to a for loop but when I debug I get an infinite loop. There are no errors when I build my solution. I'm not sure what other details to add.

Upvotes: 0

Views: 342

Answers (2)

Pranjal Mittal
Pranjal Mittal

Reputation: 69

You are using wrong variables names, value of total is increasing in the for loop so it becomes an infinite loop, use a different variable names for storing sum and for for-loop termination condition.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206567

You are increasing the value of total in the for loop. Hence, counter never reached total if you keep entering positive values.

Perhaps you meant to use sum instead of total in the loop.

for (counter = 0; counter < total; counter++)
{
    inFile >> grade;        
    cout << "The value read is " << grade << endl;
    sum = sum + grade;  
}

Upvotes: 5

Related Questions