Like Tree11Likes

Nested while loop inside for loop

This is a discussion on Nested while loop inside for loop within the C Programming forums, part of the General Programming Boards category; Guys I finished my assignment but while changing the variable names I think I messed something up and now the ...

  1. #46
    Registered User
    Join Date
    Jul 2011
    Posts
    38
    Guys I finished my assignment but while changing the variable names I think I messed something up and now the calculations are wrong and I seriously can't figure out what happened. For instance, when I enter in 15 for the first section and 30 for the second section, it should add them up to 45 and then divide them by 2 to get the school average but it messes that part up for some reason!

    The program works fine all except for the calculations. If you run the program you'll see what i'm talking about.

    Code:
    #include <stdio.h>
    
    int main(void)
    {
    
    int sCode, studID, m, loop = 0, loopS = 0;
    float mark, totalPrint, totalStored, averageSection = 0, averageSchool = 0;
    
    
    printf("\n\nEnter the Section Code: ");
    scanf("%d", &sCode);
    do{
      totalStored = 0;
      loopS++;
    
      while (sCode > 4 || sCode < 1)
      {
        printf("Invalid value entered. Must be 1 to 4, please re-enter: ");
        scanf("%d", &sCode);
      }
      
      printf("Enter the Student's ID: ");
      scanf("%d", &studID);
      do {
        totalPrint = 0;
        loop++;
      for (m = 1; m < 6; m++)
        {
          printf("Enter Mark #%d: ", m);
          scanf("%f", &mark);
          while (mark > 20 || mark < 0)
          {
            printf("Invalid grade entered. Must be 0.0 to 20.0, please re-enter: ");
            scanf("%f", &mark);
          }
          totalStored = totalStored + mark;
          totalPrint = totalPrint + mark;
          averageSection = (totalStored / (loop * 100)) * 100;
        }
    
        printf("%d's total mark is: %.2f\n", studID, totalPrint);
        printf("Enter the Student's ID ['0' to quit]: ");
        scanf("%d", &studID);
      } while (studID != 0);
    
    averageSchool = (averageSchool + averageSection) / loopS;
    
    printf("Enter the Section Code ['0' to quit]: ");
    scanf("%d", &sCode);
    printf("\nThe average for the section is: %.2f%\n\n", averageSection);
    } while (sCode != 0);
    
    printf("\nThe average for the course is: %.2f%\n\n", averageSchool);
    
    }
    Last edited by Sonny; 07-31-2011 at 06:55 PM.

  2. #47
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Quote Originally Posted by Sonny View Post
    Code:
      do {
        totalPrint = 0;
        loop++;
      for (m = 1; m < 6; m++)
        {
          printf("Enter Mark #%d: ", m);
          scanf("%f", &mark);
          while (mark > 20 || mark < 0)
          {
            printf("Invalid grade entered. Must be 0.0 to 20.0, please re-enter: ");
            scanf("%f", &mark);
          }
          totalStored = totalStored + mark;
          totalPrint = totalPrint + mark;
          averageSection = (totalStored / (loop * 100)) * 100;
        }
    
        printf("%d's total mark is: %.2f\n", studID, totalPrint);
        printf("Enter the Student's ID ['0' to quit]: ");
        scanf("%d", &studID);
      } while (studID != 0);
    
    averageSchool = (averageSchool + averageSection) / loopS;
    
    printf("Enter the Section Code ['0' to quit]: ");
    scanf("%d", &sCode);
    printf("\nThe average for the section is: %.2f%\n\n", averageSection);
    } while (sCode != 0);
    
    printf("\nThe average for the course is: %.2f%\n\n", averageSchool);
    
    }
    Your averageSection (in red) is being calculated for every students mark vice each section - which is what you want it to do. Now, if you don't want it to calculate over for each mark (aka each pass through your for loop) where would you put it?
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  3. #48
    Registered User
    Join Date
    Jul 2011
    Posts
    38
    Quote Originally Posted by AndrewHunter View Post
    Your averageSection (in red) is being calculated for every students mark vice each section - which is what you want it to do. Now, if you don't want it to calculate over for each mark (aka each pass through your for loop) where would you put it?
    I have no clue bud, i'm in the dark here.

  4. #49
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Ok, I will give you a hint: You do not want the part in red to be in your for loop. Now you have a 50/50 chance on where you are going to put it. Pick one, try it out and see what happens.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  5. #50
    Registered User
    Join Date
    Jul 2011
    Posts
    38
    Quote Originally Posted by AndrewHunter View Post
    Ok, I will give you a hint: You do not want the part in red to be in your for loop. Now you have a 50/50 chance on where you are going to put it. Pick one, try it out and see what happens.
    I have tried putting it everywhere, before the for loop after the for loop and the average for the school is still the same. :s

    Are you sure it has something to do with the placement of;
    averageSection = (totalStored / (loop * 100)) * 100;

    No matter where I put it the final calculations are always messed up.
    Last edited by Sonny; 07-31-2011 at 07:24 PM.

  6. #51
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    ok, look at your code and think about it:

    1. Your for loop is for each student. So anything in your for loop should only be for the student. Just below that loop is the calculation for averages for the student.
    2. Your inner do-while loop is for each section. So anything in that loop should be for the section. Just below that needs to be calulation for averages for the section.
    3. Your outer do-while loop is for the school. Anything in that loop should be for the school. Just below that loop should be calculations for averages for the school.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  7. #52
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    So:
    Code:
    do{
         ask for section info
         do{
              ask for student info
              for student marks{
                   get student marks
                   maintain total for marks
              }
              calculate student average
              maintain section total
         }
         calculate section average
         maintain total school
    }
    calculate school average
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  8. #53
    Registered User
    Join Date
    Jul 2011
    Posts
    38
    Quote Originally Posted by AndrewHunter View Post
    ok, look at your code and think about it:

    1. Your for loop is for each student. So anything in your for loop should only be for the student. Just below that loop is the calculation for averages for the student.
    2. Your inner do-while loop is for each section. So anything in that loop should be for the section. Just below that needs to be calulation for averages for the section.
    3. Your outer do-while loop is for the school. Anything in that loop should be for the school. Just below that loop should be calculations for averages for the school.
    Ok so should the section calculation be inside the nested do-while loop? Same with the course calculation or outside their respective do-while loops?

  9. #54
    Registered User
    Join Date
    Jul 2011
    Posts
    38
    Quote Originally Posted by AndrewHunter View Post
    So:
    Code:
    do{
         ask for section info
         do{
              ask for student info
              for student marks{
                   get student marks
                   maintain total for marks
              }
              calculate student average
              maintain section total
         }
         calculate section average
         maintain total school
    }
    calculate school average

    Code:
      do {
        totalPrint = 0;
    
        for (m = 1; m < 6; m++)
        {
          printf("Enter Mark #%d: ", m);
          scanf("%f", &mark);
          while (mark > 20 || mark < 0)
          {
            printf("Invalid grade entered. Must be 0.0 to 20.0, please re-enter: ");
            scanf("%f", &mark);
          }
          totalStored = totalStored + mark;
          totalPrint = totalPrint + mark;
    	  
        }
    
        printf("%d's total mark is: %.2f\n", studID, totalPrint);
        printf("Enter the Student's ID ['0' to quit]: ");
        scanf("%d", &studID);
      
      } while (studID != 0);
      averageSection = (totalStored / (loop * 100)) * 100;
    
    
    printf("Enter the Section Code ['0' to quit]: ");
    scanf("%d", &sCode);
    printf("\nThe average for the section is: %.2f%\n\n", averageSection);
    } while (sCode != 0);
    averageSchool = (averageSchool + averageSection) / loop;
    printf("\nThe average for the course is: %.2f%\n\n", averageSchool);
    I changed em to where you told me but still no luck.
    Maybe if you could tell me what you meant by maintain total?
    Last edited by Sonny; 07-31-2011 at 08:00 PM.

  10. #55
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    The outline I gave you was general. You need to reset your counters as well. Ok, you know what look at this. NOTE: I did not do percentages for this. I am sure you can figure out that math
    Code:
    #include <stdio.h>
    
    int main(void)
    {
    
    	int sCode, studID, m, loop = 0, loopS = 0;
    	float mark, totalPrint, totalStored, totalSchool=0,averageSection = 0, averageSchool = 0;
    
    
    	printf("\n\nEnter the Section Code: ");
    	scanf("%d", &sCode);
    	do{
    		totalStored = 0;
    		averageSection = 0;
    		loop = 0;
    		loopS++;
    
    		while (sCode > 4 || sCode < 1){
    			printf("Invalid value entered. Must be 1 to 4, please re-enter: ");
    			scanf("%d", &sCode);
    		}
      
    		printf("Enter the Student's ID: ");
    		scanf("%d", &studID);
    		do{
    			totalPrint = 0;
    			loop++;
    			for (m = 1; m < 6; m++){
    				printf("Enter Mark #%d: ", m);
    				scanf("%f", &mark);
    				while (mark > 20 || mark < 0){
    					printf("Invalid grade entered. Must be 0.0 to 20.0, please re-enter: ");
    					scanf("%f", &mark);
    				}
    				totalPrint = totalPrint + mark;
    			}
    			totalStored = totalStored + totalPrint;
    			printf("%d's total mark is: %.2f\n", studID, totalPrint);
    			printf("Enter the Student's ID ['0' to quit]: ");
    			scanf("%d", &studID);
    		} while (studID != 0);
    		
    		averageSection = (totalStored / loop);
    		totalSchool = totalSchool + averageSection;
    		printf("\nThe average for the section is: %.2f%\n\n", averageSection);
    		
    		printf("Enter the Section Code ['0' to quit]: ");
    		scanf("%d", &sCode);
    
    	} while (sCode != 0);
    	
    	averageSchool = (totalSchool / loopS);
    	printf("\nThe average for the course is: %.2f%\n\n", averageSchool);
    
    	
    	return (0);
    }
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  11. #56
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Sonny ... Stop Guessing!

    It looks for all the world like as soon as you have the slightest problem, you just start randomly bumbling around trying stuff without even knowing why you're trying it... This is not going to work!

    When things go wrong stop and THINK about it, work out what's wrong and why... Then create a solution.

    As we've told you at least a dozen times... you cannot solve a problem you do not understand. The key here is to take the time to understand... don't just start screwing with your code.
    Last edited by CommonTater; 07-31-2011 at 08:43 PM.
    AndrewHunter likes this.

  12. #57
    Registered User
    Join Date
    Jul 2011
    Posts
    38
    Quote Originally Posted by CommonTater View Post
    Sonny ... Stop Guessing!

    It looks for all the world like as soon as you have the slightest problem, you just start randomly bumbling around trying stuff without even knowing why you're trying it... This is not going to work!

    When things go wrong stop and THINK about it, work out what's wrong and why... Then create a solution.

    As we've told you at least a dozen times... you cannot solve a problem you do not understand. The key here is to take the time to understand... don't just start screwing with your code.
    I know dude haha, i've been trying to figure out what's wrong for over 3 hours now and my assignment is due tomorrow. I'm stressing out right now no time to go through it and plan it out again. :P

  13. #58
    Registered User
    Join Date
    Jun 2011
    Posts
    2,652
    CommonTater makes a great point.

    I'd like to add ... Untangling code in the text editor can be difficult, at times - sometimes leading to the habit of just moving things around until it works.

    Have you sat down with a pen and paper during the construction of this code? This is what personally helps me the most with solving difficult problems. Go through your code and write down variable values, working out the results by hand. Do not glaze over any commands - meticulously take each statement into account. Don't be afraid to draw crude diagrams to help illustrate/visualize what is going on. More often than not, while a bit tedious, this will result in clearly highlighting any problem behavior.

    EDIT: Deadline pressure will do nothing to help you. It's important - but putting it out of your mind is probably the only way you're going to be able to pull through so quickly.

  14. #59
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Sonny View Post
    I know dude haha, i've been trying to figure out what's wrong for over 3 hours now and my assignment is due tomorrow. I'm stressing out right now no time to go through it and plan it out again. :P
    You don't have to... Go back to your original plan, look at your code... figure out where your mistake is, then fix it.

    I GUARAN-DARN-TEE that if you spend 5 minutes thinking it through, you'll save yourself hours of making even more mistakes....

    I once new an RC Modeler who would get so far into a project, make a mistake, trash it and start over. He didn't have the first clue about trouble-shooting. My cousin, also an avid RC Pilot, took a half dozen of this guy's "failed projects" home and after minor repairs, he flew every one of them!

    As the back cover of the Hitchiker's Guide To The Galaxy says: Don't Panic!.
    Last edited by CommonTater; 07-31-2011 at 08:58 PM.
    AndrewHunter likes this.

  15. #60
    Registered User
    Join Date
    Jul 2011
    Posts
    38
    Quote Originally Posted by Matticus View Post
    CommonTater makes a great point.

    I'd like to add ... Untangling code in the text editor can be difficult, at times - sometimes leading to the habit of just moving things around until it works.

    Have you sat down with a pen and paper during the construction of this code? This is what personally helps me the most with solving difficult problems. Go through your code and write down variable values, working out the results by hand. Do not glaze over any commands - meticulously take each statement into account. Don't be afraid to draw crude diagrams to help illustrate/visualize what is going on. More often than not, while a bit tedious, this will result in clearly highlighting any problem behavior.

    EDIT: Deadline pressure will do nothing to help you. It's important - but putting it out of your mind is probably the only way you're going to be able to pull through so quickly.
    That's the thing this isn't a difficult problem, but it's just the little things that are getting me into trouble. I wrote the program myself and only in the most direst circumstance when every other option I have has been spent do I ask for help.

Page 4 of 5 FirstFirst 12345 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. change var inside loop and run loop again
    By d387420489 in forum C Programming
    Replies: 5
    Last Post: 07-29-2011, 02:19 AM
  2. For Loop inside While Loop
    By mesmer in forum C Programming
    Replies: 1
    Last Post: 11-29-2008, 12:29 PM
  3. for loop ignoring scanf inside loop
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-17-2007, 02:46 AM
  4. for loop inside of a for loop
    By pippen in forum C++ Programming
    Replies: 5
    Last Post: 03-28-2003, 04:11 PM
  5. Nested Loop
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 05-07-2002, 01:40 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21