-1

I don't know much about modularity except it's basically dividing up your code into smaller groups of functions (this question is for the C language).

I'm doing an assignment where I can only see my source code working with one giant nested loop in "main" (no if statements are allowed for the assignment). In other words, if I try and use functions to cut up the code, I don't see how the necessary nested loop will work. But the assignment requires an attempt at modularity.

Thus, can anyone tell me how I might break up the following code into smaller modules without messing up its actual execution?

#include <stdio.h>

int main(void)
{
   int counter = 0;
   int marknum = 0;
   int sectioncode, studentnumber;
   int dummyvariable = 0;
   int index;
   int marks;
   int total = 0;

   do
   {
      printf("Enter a Section Code: ");
      scanf("%d", &sectioncode);

      while(sectioncode > 4 || sectioncode < 1)
      {
         printf("Invalid value entered. Must be 1 to 4, please re-enter: ");
         scanf("%d", &sectioncode);
      }

      do
      {
         printf("Enter the Student's ID: ");
         scanf("%d", &studentnumber);

         while (studentnumber < 1 || studentnumber > 999999999)
            {
               printf("Invalid value entered. Must be 1 to 999999999. Please re-enter: ");
               scanf("%d", &studentnumber);
            }

         while (sectioncode != 0)
        {
           while (counter < 5)
           {
              counter++;
              marknum++;
              printf("Enter mark%d: ", marknum);
              scanf("%d", &marks);
              total = total + marks;
           }

           printf("%09d's total mark is %d\n", studentnumber, total);
           counter = 0;
           marknum = 0;
           sectioncode = 0;
        }

      dummyvariable = 1;

   } while (dummyvariable = 0);

} while (sectioncode != 0);

   return 0;
}

Also, how would I incorporate modularity for this one (same question basically):

#include <stdio.h>

int main(void)
{
   int num;                                                      //User inputted number
   int i;                                                        //Increment variable
   char ch;                                                      //Check for characters variable

      do                                                         //Begin "do while" loop
      {
      printf("\nEnter a number:");                               //User prompt
      scanf ("%d", &num);                                        //Scan for user inputted integer
      while ( (ch = getchar()) != '\n')                          //Scan for character, check for non-numeric input
         {
            printf("Invalid number entered. Please re-enter: "); //Error message and prompt for invalid user input
            scanf ("%d", &num);                                  //Scan for user inputted integer
         }                                                       //Repeat loop if condition becomes true again

      for (i=0; i<num; i++)                                      //Begin "for" loop; condition prints asterisks equal to user number; increment i by 1
         {
            printf("*");                                         //Prints a single asterisk each loop until i is less than num
         }
      } while (num!=0);                                          //Stop "do while" loop if user enters 0

return 0;
}
J. Chomel
  • 8,193
  • 15
  • 41
  • 69
  • 1
    Honestly, I'm trying to make sense of your existing loops in the first place. In particular the lack of it pertaining to the `while (sectioncode != 0)` loop and the `while (dummyvariable = 0);` *assignment* loop condition. Regardless, clearly gathering a proper section code, and likewise proper student id, could be isolated to their own functions. Honestly if your code *works*, it belongs on [codereview.stackexchange.com](http://codereview.stackexchange.com) to field questions like yours. – WhozCraig Sep 05 '16 at 03:12
  • The second fragment can be split into two subordinate functions plus main. The first subordinate function would read and return a number. It should take a few more precautions (EOF, for example). The second subordinate function would be the printing loop. Those are simple. You should review the merits of `putchar('*');` vs `printf("*");`. – Jonathan Leffler Sep 05 '16 at 05:46
  • Note that your line `} while (dummyvariable = 0);` at the end of a `do { … } while` loop is going to cause the loop to terminate each time, because that is an assignment, not a comparison. The `dummyvariable = 1;` assignment immediately before it is irrelevant. – Jonathan Leffler Sep 05 '16 at 05:49
  • "Modularity" or "object-orientation" or call it what you will, is about splitting up code in autonomous modules based on their designated purpose. The benefits are readability, ease of maintenance and code-reuse, particularly for large projects. In your example it might have made sense to create a student module, containing all data and calculations related to students. And perhaps another module for the GUI. But this is such a tiny program that you would normally not bother with any form of program design. – Lundin Sep 05 '16 at 06:01
  • 1
    What we see here is a perfect example of why restrictions like "no if statements are allowed for this assignment" are idiotic. Whoever is giving you that assignment is IMO not to be trusted (read: get a better source for learning). – Daniel Jour Sep 05 '16 at 08:13

1 Answers1

0

Normally I'd suggest that you ask your instructor instead of asking homework questions here, but as Daniel points out in the comments, the use of loops and extra variables just to avoid having if statements in the code is stupid, and I'm not sure telling you to get advice from an instructor who thought that was a good idea would be entirely responsible behavior on my part. So, having said that:

What you want to look for in cases like this is multiple chunks of similar code, or chunks of code that conceptually do a single thing. Then see if you can split those chunks out into a function.

In the first example, you display a prompt, read user input, and verify the input for both sectioncode and studentnumber. That process could be split into a separate function. (Everything from printf("Enter ...") through the end of the while loop.) Then in the main function, you just have something like

sectioncode = readval("Enter a Section Code: ", 1, 4);
studentnumber = readval("Enter the Student's ID: ", 1, 999999999);

For the second example, that input/validation code isn't duplicated, but it's still probably worth splitting out into a function, since it does a single well-defined thing, and spans enough lines that splitting it out into a function might help make the logic of the remaining code more clear. But it's less important in this case than in the first.


Also, an unrelated issue: At the end of one of the do-whiles, you have while (dummyvariable = 0);. Note the single equal sign. You're assigning 0 to dummyvariable, not comparing.

In this particular case, it works anyway, since the whole expression evaluates to 0 (i.e. false), just like (dummyvariable == 0) would have. But if that constant had been anything else, or if you hadn't just set dummyvariable to 1 prior to the end of loop, that'd be a bug.

I strongly recommend always putting the constant on the left hand side of expressions like that in order to catch bugs of that sort at compilation. while (dummyvariable = 0) silently does something unexpected; while (0 = dummyvariable) will give an error at compile-time, and you can fix it.

Ray
  • 1,706
  • 22
  • 30