You are here:

C++/For loop for devc++

Advertisement


Question
Hi I have a question I'm having trouble writing code using a for loop that does this :


using namespace std;
int test_1, test_2, test_3, test_4;
double average = 0;
double total_grade = 0;

int main()
{
    cout << "Enter grade 1 ";
    cin >> test_1;
    cout << "Enter grade 2 ";
    cin >> test_2;
    cout << "Enter grade 3 ";
    cin >> test_3;
    cout << "Enter grade 4 ";
    cin >> test_4;
   
   total_grade = test_1+test_2+test_3+test_4;
   average = total_grade / 4;
   cout << "The average is: ";
   cout << average;

Any help would be appreciated...
Thank you

Answer
First I am wondering why you are using global variables rather than local variables. In a small program such as this it does not really matter, but global data causes problems in larger systems, so it is good to get into the habit of _not_ using it when not absolutely necessary, so move the variable definitions inside of main thus:

using namespace std;

int main()
{
   int test_1, test_2, test_3, test_4;
   double average = 0;
   double total_grade = 0;

   cout << "Enter grade 1 ";

// ...

Next I would have liked to see your attempt at a for-loop for the above code. If nothing else it would help me see what it is you are having a problem with.

No matter. I'll assume you know little about for loops. A for-loop, like all loops repeat a section of code until some condition is met. The simplest loop construct in C and C++ is the while-loop which has the form:

   while ( expression-is-true )
   {
   // repeat the code
   }

In which the code in braces is repeated until expression-is-true is false.

A for-loop is more complex it has the form:

   for ( initial-expression ; expression-is_true ; end-expression )
   {
   // repeat the code
   }

It is equivalent to the following:

   initial-expression;

   while ( expression-is-true )
   {
   // repeat the code

       end-expression;
   }

Any or all of the three expressions forming the for-statement may be omitted but the semicolons must remain. If the initial-expression or end-expression is omitted it is as if it were not in the logical while loop equivalent. If the expression-is-true part is omitted then it is taken to be true, so:

   for (;;;)
   {
   // repeat code forever
   }

Will repeat the code in the braces forever, equivalent to:

  while (true)
  {
  // repeat code forever
  }

I have shown the repeated code in braces. In fact if there is only one statement it can follow without braces:

   for (;;;)
       ;// repeat single statement forever
   
A for-loop is typically used in situations where we progress through a sequence from a start point to an end point. The simplest example is to count from a start value to an end value. To loop N times we could count from 1 to N, the true expression being "count is not greater than N" and the end expression would add 1 to count. C and C++ people prefer starting at 0 rather than 1 so it is more common to count from 0 to N-1, in which case then true condition is "while count is less than N" or "while count is not equal to N". You should also be aware that it is also common to use a count variable with a single letter starting with i, then j if i is in use, then k etc. I think this is a hang over from the early days of FORTRAN where such variable names were integer types, whereas a, b, c, x, y, x etc. were floating point types. i could also be short for index, a common use for such values.

So let us apply this information to your problem. You need to loop around 4 times (you have 4 grades to average), so we need to count from 0 to less than 4, adding 1 to the count each time around the loop. Representing this using the while loop equivalent form of a for-loop could look like this:

   int count = 0;  // initial-expression

   while ( count < 4 ) //  count < 4 is expression-is-true
   {
   // Do processing

       ++count; // add 1 to count: end-expression
   }

Re-phrasing as a for-loop we get:

   for ( int count = 0; count < 4; ++count )
   {
   // Do processing
   }

Or, using the "while count not equal to N" form of the test:

   for ( int count = 0; count != 4; ++count )
   {
   // Do processing
   }

So what processing would you need to do? Well you need to prompt the user and get each value from them, but how would you store the answers? Do you really need each answer? What are you going to do to them?

First let us look at getting a value form the user. Here the prompt reflects the number of the item being entered: 1, 2, 3 or 4. Our loop generates numbers: count has the value 0, 1, 2 and 3. Up until now it has not been used for anything other than keeping track of when we are done, so using the usual C/C++ convention of starting from 0 seemed a good idea. However now we would like some numbers 1, 2, 3, and 4 so we can display the number of the grade value being entered to the user. We shall modify the loop to fit in with our needs, and ask the user for data:

   for ( int count = 1; count <= 4; ++count )
   {
       cout << "Enter grade " << count << " ";

   // Do further processing
   }

Let us now look at getting, storing and processing values.

In your posted code you ask for 4 values, you get them and you store each in its own variable. Then you add them all together and divide by 4. That is you obtain the average from the data by summing all the data and diving by the number of pieces of data. So all you need to obtain the average is the sum of the data and the number of pieces of data. This last is fixed at 4. So all we need to arrange is to get you the sum of the values entered by the user. You do not in fact need each piece of data beyond its contribution to the sum. We can build the sum by accumulating it as we get each piece of data from the user each time around the loop:

   double total_grade = 0;
   
   for ( int count = 1; count <= 4; ++count )
   {
       cout << "Enter grade " << count << " ";
       int test_grade = 0;
       cin >> test_grade;
       total_grade += test_grade; // accumulate sum of test grades
   }

When the loop terminates total_grade will contain the sum of all the individual test grades. All that remains is to produce and display the average as before:

   average = total_grade / 4;
   cout << "The average is: ";
   cout << average;

Now the number 4 appears in at least 2 places in your code with the same meaning. It is a magic number and can mean anything. If another factor were also to have the value 4 (but unrelated to the number of test grades) and suddenly there were 6 tests not 4 then to someone updating the code it is not clear which existing uses of 4 need to be changed to 6. It is best to name magic numbers using a constant:

   int const NumberOfTests = 4;

   double total_grade = 0;
   
   for ( int count = 1; count <= NumberOfTests; ++count )
   {
       cout << "Enter grade " << count << " ";
       int test_grade = 0;
       cin >> test_grade;
       total_grade += test_grade; // accumulate sum of test grades
   }

   average = total_grade / NumberOfTests;
   cout << "The average is: ";
   cout << average;

Now changing only the value of NumberOfTests from 4 to 6 and rebuilding the program will make it work for 6 test grades rather than 4.

This effectively does your assignment for you. If you post such questions in future I wish to see your efforts in what ever area you are having problems with, even if they are just sketchy thoughts and half formed code, just so I know you are using your brain and trying your hardest and not just trying to sucker me into doing your assignments for you. If you do not I am likely to reject your question.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.