if statement won't work - comparing INT variables from same array...?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17

Thread: if statement won't work - comparing INT variables from same array...?

  1. #1
    Join Date
    Dec 2010
    Posts
    7

    if statement won't work - comparing INT variables from same array...?

    Hello,

    I am a student and I'm having trouble figuring out why my if statement won't evaluate. I'm not getting any error in my compiler - I'm using Dev-C++ 4.9.9.2

    The if statement in question is on line #160 in the code below (full code). You will need the students.txt file also if you plan to run this - I included it's contents at the bottom.

    Code:
    #include <iostream>
    #include <fstream>
    #include <iomanip>
    #include <string>
    
    using namespace std;
    
    const int NO_OF_STUDENTS = 6;
    
    struct studentType
    {
      string studentFName;
      string studentLName;
      int testScore[4];
      char grade[4];
    };
    
    int highScore[4];
    
    int topScores[6][4];
    
    void initialize(ifstream& indata, studentType list[], int listSize);
    void processScores(studentType list[], int listSize);
    
    int main()
    {
     ifstream infile;
     string inputFile;
     studentType studentList[NO_OF_STUDENTS];
    
     cout << "Enter the file name for file containing all test records: ";
     cin >> inputFile;
     cout << endl;
    
     infile.open(inputFile.c_str());
    
     if(!infile)
     {
      cout << "Cannot open the input file." << endl;
      return 1;
     }
    
     initialize(infile, studentList, NO_OF_STUDENTS);
     processScores(studentList, NO_OF_STUDENTS);
     
     infile.close();
    
    // The following 6 lines of code delays termination of the program until
    // the user presses the enter key. This is a convenience for those using
    // a windows environment but it will work on every platform.  
    char any_keystroke;
    //reads and ignores up to 200 characters, or '\n' is read and ignored
    cin.ignore(200, '\n');                                                                
    cout << "\n\n";
    cout << "Program execution has ended normally.\n";
    cout << "Press the enter key to exit.";
    cin.get(any_keystroke);
    
    return 0;
    }
    
    void initialize(ifstream& indata, studentType list[], int listSize)
    {
         int index;
         int allTestScores;
    
         for (index = 0; index < listSize; index++)
         {
             indata >> list[index].studentFName;
             cout << "fname: " << list[index].studentFName << endl;
             indata >> list[index].studentLName;
             cout << "lname: " << list[index].studentLName << endl;
             for (allTestScores = 0; allTestScores < 4; allTestScores++)
             {
               indata >> list[index].testScore[allTestScores];
               // begin assigning letter grades
               if(0 <= list[index].testScore[allTestScores] && list[index].testScore[allTestScores] <= 50)
                 list[index].grade[allTestScores] = 'F';
               else if (51 <= list[index].testScore[allTestScores] && list[index].testScore[allTestScores] <= 65)
                 list[index].grade[allTestScores] = 'D';
               else if (66 <= list[index].testScore[allTestScores] && list[index].testScore[allTestScores] <= 75)
                 list[index].grade[allTestScores] = 'C';
               else if (76 <= list[index].testScore[allTestScores] && list[index].testScore[allTestScores] <= 89)
                 list[index].grade[allTestScores] = 'B';
               else
                 list[index].grade[allTestScores] = 'A';
             
               cout << "test score: " << list[index].testScore[allTestScores] << " " << list[index].grade[allTestScores] << endl;
             }
             cout << endl;
             cout << "Student #:" << index << endl;
         }
         cout << "Preparing Grades for Processing..." << endl;
         cout << endl << endl;
    }
    
    void processScores(studentType list[], int listSize)
    {
         int index;
         int allTestScores;
         int maxXIndex = 0;
         int maxYIndex = 0;
         int absoluteHighest = 0;
         int count = 0;
         int highByStudent[listSize][4];
         int highByTest[listSize][4];
         
         cout << "Begin Grade Processing..." << endl;
         cout << "Found " << listSize << " students.." << endl;
         cout << endl << endl;
         
         // start initialization of category arrays.  This sets all values within the array to 0.
         for (index = 0; index < listSize; index++)
         {
             if (index == 0)
             {
               cout << " Entering Scores Array Initialization Loop. " << endl;
               cout << "<------------------------------------------>" << endl;
             }
             cout << "Row #" << index << ": ";
             for (allTestScores = 0; allTestScores < 4; allTestScores++)
             {
               highByTest[index][allTestScores] = 0;
               cout << highByTest[index][allTestScores] << " ";
               
             }
             cout << endl;
             if (index == 5)
             {
               cout << "<------------------------------------------>" << endl;
               cout << endl;
             }
         }
         for (index = 0; index < listSize; index++)
         {
           cout << "Row #" << index << ": ";
           for (allTestScores = 0; allTestScores < 4; allTestScores++)
             {
               highByStudent[index][allTestScores] = 0;
               cout << highByStudent[index][allTestScores] << " ";
             }
             cout << endl;
             if (index == 5)
             {
               cout << "<------------------------------------------>" << endl;
               cout << endl;
             }
         }
         
           if(100 > 99) { cout << "100 is greater than 99"; }
           if(99 > 100) { cout << "99 is greater than 100"; }
    	   // First we find the absolute highest value in the entire testScore array in this loop:
           for (index = 0; index < listSize; index++)
    	   {
             cout << "outer loop" << endl << endl;
       	     for (allTestScores = 0; allTestScores < 4; allTestScores++) 
      	     {
               cout << "inner loop" << endl;
               cout << maxXIndex << "." << maxYIndex << "." << endl << endl;
               if (list[maxXIndex].testScore[maxYIndex] < list[index].testScore[allTestScores])
                 {
                 cout << "inner loop:if" << endl;
                 cout << "Row Location of old High Score: " << maxXIndex << endl;
                 cout << "Column Location of old High Score: " << maxYIndex << endl;
                 cout << "Old High Score: " << list[maxXIndex].testScore[maxYIndex];
                 maxXIndex = index;  //Stores the Row Location of the last highest score found in the struct
                 maxYIndex = allTestScores;  //Stores the Column Location of the last highest score found in the struct
                 absoluteHighest = list[index].testScore[allTestScores]; // Stores the actual high score value
                 cout << "New High Score: " << list[index].testScore[allTestScores] << "(" << absoluteHighest << ")" << endl;
                 cout << "<------------------------------------------>" << endl;
                 cout << endl << endl;
                 count++;
                 }
             }
             
           }
           
           for (index = 0; index < listSize; index++)
         {
           cout << list[index].studentFName << list[index].studentLName << ": ";
           for (allTestScores = 0; allTestScores < 4; allTestScores++)
             {
               cout << list[index].testScore[allTestScores] << " ";
             }
             cout << endl;
             if (index == 5)
             {
               cout << "<------------------------------------------>" << endl;
               cout << endl;
             }
         }
           
           cout << "total highs: " << count << endl;
           // Print Single Highest Test Score.
           cout << "Student with Highest Score: " << list[maxXIndex].studentFName << " " << list[maxXIndex].studentLName << " - " << absoluteHighest << endl;
           
           // Find every entry that is equal to the absolute highest max score and output the student's name and the test score.
           for (index = 0; index < 4; index++)
           {
             for (allTestScores = 0; allTestScores < listSize; allTestScores++)
             {
               // begin find highest grade by test
               if (absoluteHighest = list[allTestScores].testScore[index])
               {
                 highByTest[allTestScores][index] = list[allTestScores].testScore[index];
                 highByTest[allTestScores][index] - list[allTestScores].testScore[index];
               }
             }
           }
    }
    "students.txt" (name it whatever you want, the program prompts you for the file name):

    Code:
    seth wb 89 99 98 97
    missy peterson 97 98 99 100
    roger hampton 55 87 65 75
    samilla achebe 88 66 76 100
    shereth balasubramanian 100 100 99 99
    maria montessori 100 100 100 100
    Please help me understand what I am doing wrong here so I can fix it!

    Thanks in advance,
    Seth

  2. #2
    Join Date
    Apr 2008
    Posts
    726

    Re: if statement won't work - comparing INT variables from same array...?

    doesnt even compile. arrays should be compile time constant size.

    what are you doing here:
    highByTest[allTestScores][index] - list[allTestScores].testScore[index];
    ?

    It doesnt actually do anything

    As for your if statement on #160, it evaluates perfectly fine. I suggest you use a debugger - the answer will be very obvious
    Last edited by Amleto; March 22nd, 2011 at 06:47 PM.

  3. #3
    Join Date
    Dec 2010
    Posts
    7

    Re: if statement won't work - comparing INT variables from same array...?

    That was a typo... that entire function isn't done yet.

    Also, this is really weird but after I posted this I went back and recompiled the program without changing anything and it worked. I still have no idea what I did wrong.

  4. #4
    Join Date
    Aug 2009
    Posts
    439

    Re: if statement won't work - comparing INT variables from same array...?

    Just another thing, DevC++ is very old. I'd suggest a more up to date IDE. Try Code::Blocks (it's free).

  5. #5
    Join Date
    Dec 2010
    Posts
    7

    Re: if statement won't work - comparing INT variables from same array...?

    Now that we're here though I might as well ask about the statement you pointed out.

    The last two for loops are supposed to go through and mark every instance it finds of the highest Scores, then output them on screen. Do you know of any easier way to locate all high scores in a multidimensional array?

  6. #6
    Join Date
    Dec 2010
    Posts
    7

    Re: if statement won't work - comparing INT variables from same array...?

    Sorry I forgot to include the updated code for that last for loop:

    Code:
    for (index = 0; index < 4; index++)
           {
             cout << "Highest test scores for test #" << index << ":" << endl;
             for (allTestScores = 0; allTestScores < listSize; allTestScores++)
             {
               // begin find highest grade by test
               if (absoluteHighest == list[allTestScores].testScore[index])
               {
                 cout << list[allTestScores].studentFName << list[allTestScores].studentLName << ": " << list[allTestScores].testScore[index] << endl;
               }
             }
             cout << endl;
           }

  7. #7
    Join Date
    Aug 2009
    Posts
    439

    Re: if statement won't work - comparing INT variables from same array...?

    Perhaps a better approach is to use an array or vector to store each students max score. The easiest way would be to do this on the fly. You compare the max to the current test score and assign as needed. You can use a structure and have one part be the max score, the next be the number of times that shows up for a particular student. Then, you can go through each students personal max and determine who has the highest score. In the event of a tie, use the number of high score counts to determine the "highest." As of now Missy Peterson is listed as the person with the highest score, seems it should be Maria Montessori. Hope this helps.

  8. #8
    Join Date
    Dec 2010
    Posts
    7

    Re: if statement won't work - comparing INT variables from same array...?

    Well each column represents a different test. With the way I updated everything it now displays the highest test score for each student as long as it is equal to the maximum score found for each test.

    Hmm I'm a beginner so the non-vector approach would probably be easiest. I think that's basically what I did - I don't store the locations of each matching score or do it all in the same set of loops. The new array just keeps track of the highest test score for each test, I then use it later to match all high scores = to it then output those next to the student's name.

    Are you suggesting that there is a way to use this array (or a vector) to complete these steps in the same set of for loops?

  9. #9
    Join Date
    Aug 2009
    Posts
    439

    Re: if statement won't work - comparing INT variables from same array...?

    I suppose let me ask you this, what is the ultimate goal of the program? To output the student with the highest score? When I run it I get seemingly useless output.


    Code:
    
    This seems like useless output. Is that the case?
    
    inner loop:if
    Row Location of old High Score: 0
    Column Location of old High Score: 0
    Old High Score: 89New High Score: 99(99)
    <------------------------------------------>
    
    
    inner loop
    0.1.
    
    inner loop
    0.1.
    
    outer loop
    
    inner loop
    0.1.
    
    inner loop
    0.1.
    
    inner loop
    0.1.
    
    inner loop
    0.1.
    
    inner loop:if
    Row Location of old High Score: 0
    Column Location of old High Score: 1
    Old High Score: 99New High Score: 100(100)
    <------------------------------------------>
    
    outer loop
    
    inner loop
    1.3.
    
    .
    .
    .
    inner loop
    1.3.
    
    
    End of seemingly useless output.
    
    sethwb: 89 99 98 97
    missypeterson: 97 98 99 100
    rogerhampton: 55 87 65 75
    samillaachebe: 88 66 76 100
    sherethbalasubramanian: 100 100 99 99
    mariamontessori: 100 100 100 100
    <------------------------------------------>
    
    total highs: 2
    Student with Highest Score: missy peterson - 100
    Highest test scores for test #0:
    sherethbalasubramanian: 100
    mariamontessori: 100
    
    Highest test scores for test #1:
    sherethbalasubramanian: 100
    mariamontessori: 100
    
    Highest test scores for test #2:
    mariamontessori: 100
    
    Highest test scores for test #3:
    missypeterson: 100
    samillaachebe: 100
    mariamontessori: 100
    Also, note above, the tests start from zero. The best approach is to add 1 to the tests for each of the outputs. I agree that listing the highest scores is a meaningful way to display the output, but I still think the student with the highest score ought to either be the one who has the highest average of scores, or the one who had the highest number of highest scores.

    Also, the cout statements I dubbed as useless appear to be a means to debug your code. It's definitely good you are thinking about this early on, but an easier approach might be to learn to use the debugger.

    As I stated with my first reply, I'd drop Dev C++ and go for either Visual Studio Express or Code::Blocks. Debugging in Code::Blocks is very easy. You simply create a breakpoint, once the code reaches the breakpoint you can step through each line. During this process you can have a window display current variable values.

    Finally, if you are not restricted in what you use, I highly recommend getting familiar with the standard library. Vectors are a good start.

  10. #10
    Join Date
    Apr 1999
    Posts
    27,423

    Re: if statement won't work - comparing INT variables from same array...?

    Code:
    highByTest[allTestScores][index] = list[allTestScores].testScore[index];
    Do not call your arrays "list". There is a std::list class in C++, so you should not call your variables the same as standard classes.
    Hmm I'm a beginner so the non-vector approach would probably be easiest.
    If you need to create the array at runtime, or if you need to add or remove elements, then the vector is not only the easier choice, it is the easiest choice.

    Regards,

    Paul McKenzie

  11. #11
    Join Date
    Apr 1999
    Posts
    27,423

    Re: if statement won't work - comparing INT variables from same array...?

    Quote Originally Posted by sethbw View Post
    Well each column represents a different test. With the way I updated everything it now displays the highest test score for each student as long as it is equal to the maximum score found for each test.
    Let's start from this simple structure:
    Code:
    #include <string>
    struct studentType
    {
      std::string studentFName;
      std::string studentLName;
      int testScore[4];
      char grade[4];
    };
    Supposedly, you have an array of these structures, correct? So from this array of structures, you want the maximum value for what exactly? Whatever that is, you don't need all of those other arrays at all.

    You want to know who has the highest score for testScore[0]?
    Code:
    struct HighScore
    {
        int whichTest;
        HighScore(int nWhich) : whichTest(nWhich) { }
        bool operator()(const studentType& s1, const studentType& s2)
        {
              return s1.testScore[whichTest] < s2.testScore[whichTest];
        }
    };
    
    #include <algorithm>
    //...
    studentType* bestStudentForGrade0 = std::max_element(studentList, studentList + NO_OF_STUDENTS, HighScore(0));
    After max_element is called, bestStudent will point to the studentType with the highest grade for test 0. For test 1:
    Code:
    studentType* bestStudentForGrade1 = std::max_element(studentList, studentList + NO_OF_STUDENTS, HighScore(1));
    Is this one of the tasks of your assignment?

    Regards,

    Paul McKenzie

  12. #12
    Join Date
    Dec 2010
    Posts
    7

    Re: if statement won't work - comparing INT variables from same array...?

    You are right - those are my debugging statements. They did not cover the use of a debugger in this class! I feel ripped off as that would have saved me many hours of debugging. Thank god this class is almost over, but my learning has only just begun apparently.

    Thank you for the thoughtful suggestions. I am downloading code::blocks now to give it a try. I had a ton of problems with getting Dev-C++ to install properly anyhow. Wish me luck I will let you know how it goes if I have any problems.

  13. #13
    Join Date
    Aug 2009
    Posts
    439

    Re: if statement won't work - comparing INT variables from same array...?

    Just to warn you, there are two types of Code::Blocks you can get...get the larger one that includes the compiler.

  14. #14
    Join Date
    Dec 2010
    Posts
    7

    Re: if statement won't work - comparing INT variables from same array...?

    Hey Paul thanks for chiming in.

    Here is the summary of my task:

    Define a struct, studentType, with the following components: studentFName of type string, studentLName of type string, and testScore of type int and grade of type char. Write a program that reads a text file that contains students' names followed by their test scores. The program should output each student's name followed by the test scores and the relevant grade. It should also find and print the highest test score and the name of the students having the highest test score.

    Obviously I goofed up the display format of the last part. Should be:

    hightest score - name, name, name

    instead of:

    name: high test score
    name: high test score
    name: high test score
    etc...


    I think it still does the job though.



    I think because I am at such an early stage of learning C++ that I basically need to go through and learn the logic behind these tasks from the ground up. Although I do appreciate you sharing built in methods for doing so already!

    As for your question - is this one of the tasks for my assignment? If by tasks you mean find a better/more efficient way of doing this, no as long as I get the job done I'll get a good grade I think the teacher is very lenient, however, for my own personal standards I'd like to learn how to do things with a high standard of efficiency in my code. When I wrote this all out I felt there had to be a better way if for no other reason than my lack of experience.

    I really appreciate you guys' input. I hope to be a really great programmer one day.

  15. #15
    Join Date
    Aug 2009
    Posts
    439

    Re: if statement won't work - comparing INT variables from same array...?

    My experience with my beginning programming courses was that they basically wanted to bumble along writing my own vector class and using arrays. I never was allowed to use vectors. Everytime I asked for help on here, I basically got the same reply: "Use the standard library!"

    This definitely isn't bad advice. If you are not restricted in your coding (for assignments) I'd try to use the standard library whenever. Why write your own vector class or linked list when there already is one. Not only that, the ones in place have been used and tested extensively.

    My advice is to try and convert what you have into using vectors.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center