Solved

Homework problem in  Intro C++

Posted on 1997-11-22
19
364 Views
Last Modified: 2012-05-05
I am enrolled in a distance education program with a major in C++.  I've been working on this problem for over a month, and am just about at my wit's end.  The problem is: "Write a program that reads 20 digit characters (i.e. characters in the range '0' ...'9') and counts the number of digits that are either 3,5, or 6 and that are either 1,4, or 9.  Those are two separate counts.  All other digits should be ignored.  Make use of the SWITCH statement."  If someone is willing to help me with this, I can e-mail the program I've written so far.

To those of you who have contacted me, I'm really not sure where the problem lies, since it seems to require both a "counter" (this is what my instructor calls it, a term that I have not been able to find in any one of a half dozen reference books) and a switch statement.  What happens at this point is that the program compiles and runs beautifully, but after I enter the numbers (as characters rather than integers) the program skips directly to the first default and then miscounts the second series of numbers.

I will be glad to post the latest version if someone will tell me how to do that.  I can't figure out how to attach anything to this message.  Should I just go ahead and post my program as another message, referenced to this one?

And by the way, thanks for taking an interest.  
0
Comment
Question by:snorris3333
  • 9
  • 9
19 Comments
 
LVL 2

Expert Comment

by:rigansen
ID: 1173852
it'd be good enough to everybody if you can post it here, so anybody can see it!!

rigansen.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1173853
In addition to posting what you have so far (a good idea), you should also ask specific questions.  Right now your question is too broad and basically asks for the solution to the entire homework assignment.  It would be unethical for use to provide the entire homework assignment (and it would not be in your interest as you would not learn as much).  

Can you list a couple problem areas.  Like? how do you get the 20 digits, how do you store them, how do you write a loop that goes through the digits, how do you count the occurences, how do you list the occurances, etc.  Let us know where you need the help.
0
 

Author Comment

by:snorris3333
ID: 1173854
Edited text of question
0
 
LVL 22

Accepted Solution

by:
nietod earned 100 total points
ID: 1173855
First a counter is a numeric variable (usually a integer, but could be a character, float, or double, or other posibilites) that you use to count things with.  i.e. the name counter.  Usually it is initialized to 0 and then incremented when something is counted (there are other possibilites depending on the circumstances, but this is most common, and the way you will use it.

I'll show you how to use the counter, then if you have other problems, you can ask more questions in a comment.  This code will count only the 3,5,6 case.  You should try to add the other case.  (I can help you, but I prefer that you try, first.)

int   Cnt356    = 0;      // Number of 3's, 5's, 6's found.
char *DigStr;             // -> string of digits.
char  CurDig;             // Current character from the
                          // digit string.
char *CurDigPtr = DigStr; // -> current digit in the digit
                          // string.

***********

GetDigStr(DigStr);  // Get the digits.  
                    // I'm not sure how you get them,
                    // so this is just pseudo-code.
while (CurDigPtr)   // While there is another digit.
{
   CurDig = CurDigPtr++; // Get current digit.

   if (CurDig == '3' ||  // If the digit is a 3,5, or 6, then
       CurDig == '5' ||
       CurDig == '6')
      ++Cnt356;          // Increment the counter.
}

OutPutResult(Cnt#356);   // Again, I have no clue
                         //what you need to do here.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1173856
See if you can work with this and then try to post what you get (if you need to).  To post you code, open it up in a windows editor, of some sort (a word processor, the wordpad or notepad accessories) and then copy the code that you want to post to the clipboard.  Then you can paste the code into the comment box in your browser (on this web page) and submit a comment.
0
 

Author Comment

by:snorris3333
ID: 1173857
I'm having some trouble following your answer.  Let me go back to the drawing board and see what I can do.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1173858
I sorry you couldn't understand my answer.  The answer is very basic, so you must be really inexperienced!  (Don't worry we all were, once.)  

There are three steps to using a counter.

1.  You initialize it (give it a starting value).  In must cases, such as yours, you start it at zero.  Thus, I had the line:

int Cnt356 = 0;

This declares Cnt356 as an integer variable that will count the occurances of 3's, 5's, and 6's and it initializes the counter to 0.

2.  The next step is that you need to look for occurences of things and count them.  To count them, you increment the counter using either:

Cnt = Cnt + 1;
or
++Cnt;

If you were to write code that counted the number of pieces in a place settng of china it might look like this,

int Pieces = 0;
if (HasPlate)
   ++Pieces;
if (HasSaucer)
   ++Pieces;
if (HasTeaCup)
   ++Pieces;
if (HasSalidPlate)
   ++Pieces;
if (HasSoupBowl)
   ++ Pieces;

That code performed a bunch of seperate tests in a row.  You code performs the same test over an over again.  This is done in a loop to make it more efficient.  However inside the loop you see the same sort if logic, that is, test for a condition and if it is met increment the counter.  For example,

   if (CurDig == '3' || // If the digit is a 3,5, or 6, then
       CurDig == '5' ||
       CurDig == '6')
      ++Cnt356; // Increment the counter.

3.  The final step is to use the counter in some way.  In your case, you might just print it out like

cout << "There are " << Cnt356 << "3's, 5's and 6's."

Hope this helps.  If not, try to ask specific questions.  If you are in a hurry, I check here usually about 9 am, 2pm, 6pm central time.  Some evenings too.
0
 

Author Comment

by:snorris3333
ID: 1173859
I am in my first semester of intro to C++, and this is just the chapter 4 homework, so I'm not at all experienced.  I've probably re-done this problem fifteen times, although I managed to get this far by myself.  I'm going to try to do what you said re: cut and paste.  Here goes:

//Program Q32, CS110
//Author:  Stephanie Norris
//Date: 10/16/97

#include <iostream.h>
int main ()
      {
      char Num = '1'; '2'; '3'; '4'; '5'; '6'; '7'; '8'; '9'; '0';
      int  Count356 = 0;
      int  Count149 = 0;
      int  NumCount = 0;

      while (NumCount<20){
            ++NumCount;
            cout << "Please enter a digit between 0 and 9: "<<  endl;
            cin >> Num;
            }
            switch (NumCount) {
                  case '3':
                  cout << "The number 3 was entered "      << NumCount << " times. " << flush;

                  case '5':
                  cout << "The number 5 was entered "      << NumCount << " times. " << flush;

                  case '6':
                  cout << "The number 6 was entered "      << NumCount << " times. " << flush;
                        {++Count356; break;}

                  default :
                  cout << "The numbers 3, 5, and 6 were not entered." << endl;
                  }

            while (NumCount<20){
                  ++NumCount;
                  cout << "Please enter a digit between 0 and 9: "<<  endl;
                  cin >> Num;
                  }
                  switch (NumCount) {
                  case '1':
                  cout << "The number 1 was entered "      << NumCount << " times. " << flush;

                  case '4':
                  cout << "The number 4 was entered "      << NumCount << " times. " << flush;

                  case '9':
                  cout << "The number 9 was entered "      << NumCount << " times. " << flush;
                        {++Count149; break;}

                  default :
                  cout << "The numbers 1, 4, and 9 were not entered." << endl;
                  return 1;
                  }
            return 0;

}


Geez, I think it worked!  It's really important for me to get this counter thing down, since the remainder of the chapter problems call for the same kind of thing.

If it's any help, I'm doing this in Borland's Turbo C++ running under Win95.  I really appreciate your assistance.  I'd go ahead and give you an 'A' right now, but I'm afraid that will somehow terminate my question.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1173860
Let me propose a couple of fixes, we probaby won't get all in one try.

The line

char Num = '1'; '2'; '3'; '4'; '5'; '6'; '7'; '8'; '9'; '0';

should cause a syntax error.  you can initialize a varaible to only one value, like

char Num = '1';

You can't have multiple values.  In addition, you don't need to initialize Num, since it will be entered by the user.  So just use the line

char Num;
*************************
Now there are two ways to approach this task.  you can get one digit from the user a time.  Process the digit and get the next  That would look a little like this,

while (NumCount < 20)
{
    // Get a digit.
    switch ()
    {
    // stuff
    };
    ++NumCount;
}
// print results.

The other approach is to get all the digits from the user and store them.  Then process them one at a time.  That would look a little like this

while (NumCount < 20)
{
    // Get a Digit.
    ++NumCount;
}
NumCount = 0;
while (NumCount < 20)
{
    switch ()
    {
    // stuff
    };
    ++NumCount;
}

to summarize, you can have one loop where you can get and process a digit or you can hoave two loops where the first one gets the digits and the second one processes them.  Your code kinda stratles both.  I'll assume you want to go to using one loop.

That means the digit processing logic (switch statement, etc) needs to be put in the loop.
***********************************
Now for the switch statement.  The purpose of the switch statement is (in this case) to evaluate what the current digit is and alter the counters to record what it discovers.  It should not print out the anything.  Why?  because you are not done.  You need to process 20 digits before you print out your results.  The  switch statement will execute 20 times, once for each digit, then you print the results.

The switch statement must switch base on the value in "Num", that is, the digit entered by the user, not the value in "NumCount".  I assume this is obvious to you so I won't explain.  If not, let me know.

I will do part of the switch statement and the while loop, you do the rest.

while (NumCount<20)
{
   ++NumCount;
   cout << "Please enter a digit between 0 and 9: "<< endl;
   cin >> Num;
   switch (Num)
   {
   case '3':
   case '5':
   case '6':
      ++Count356;
      break;
   }
}
// now print results.

Try these fixes.  If you can't get it working, post your new code and soem questions.
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 22

Expert Comment

by:nietod
ID: 1173861
No response?  Was that too hard to understand?
0
 

Author Comment

by:snorris3333
ID: 1173862
I haven't had a chance to work on this problem since you left your comments.  Aside from being a student, I'm a CPA and I had to go to a seminar today to complete my CPE credits for this bi-annual period.  And then, of course, there's the ever-present nuisance of having to make a living while I try to switch fields. That's been known to get in the way of doing homework!

However, your explanations are much more intelligible than anything else I've seen, including my textbook.  I'll be working on this problem tonight and tomorrow.  Many thanks for your help.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1173863
Is see.  I was under the impression that you were a REAL student.  I should have known, though.  REAL students.

A.  Always use the word "Urgent" in their question.
B.  Never admit that the question is a homework assignment.

A CPA programmer?  An interesting idea.  I wonder what would happen if someone who actually understood accounting were to write an accounting program.  
0
 

Author Comment

by:snorris3333
ID: 1173864
I'm not sure if that was an insult or not.  I'll assume *not*.  Yes, I've often wondered too what tax programs would be like if a programmer who had actually done taxes ever wrote one.  I'll never forget the year TurboTax automatically calculated Social Security withholding by using a percentage of gross wages. It was always off a few pennies from what was on the W-2 form.  And then there's always Form 1116 (Foreign Tax Credit) that never prints out from any program I've tried even though the taxpayer is entitled to the credit and all the proper boxes have been checked.  Sure as anything, I'll forget to print it out manually and send it off to my client with the form missing.

It looks like I won't get back to my programming problem until later today, since I have to go to an eye doctor appointment this afternoon about an hour away from here (great eye doctor; I follow her everywhere), and then it's off to visit some way-out-of-town friends tomorrow.  I did look over what you sent, and also some assistance from a very talented programmer friend (your advice and his is very similar), and it looks to me like what I've been asked to do doesn't appear anywhere in my textbook.  My instructor also didn't even hint at what the real problem is.  If that's the case, I'm going to have to have some words with the school, because I've wasted all sorts of time on this.  There's no official deadline, but, in my head, I wanted to get the first C++ course finished by the end of this year.  Thanks to this problem, I doubt if I'll make it.  I've got six chapters to go!

Right now one of my make-a-living chores is converting an accounting system from QuickBooks, which is a truly wretched, badly-written accounting program, to Peachtree, which is more like textbook accounting.  Unfortunately, in order to help these people, I have to operate their accounting system under QuickBooks for a period of time, and it's close to agonizing.
0
 

Author Comment

by:snorris3333
ID: 1173865
Here's the latest.  Now it counts, but incorrectly, using the char for the NumCount ("You have entered the number 3 3 times"). Then it goes on to add ten to the NumCount ("You have entered the number 3 13 times").  What the heck, i it's an improvement!

//Program Q32
//Author:  Stephanie Norris
//Date: 10/16/97

#include <iostream.h>
int main ()
      {
      char Num;
      int  Count356 =0;
      int  Count149 = 0;
      int  NumCount = 0;

      while (NumCount<20){
            ++NumCount;
            cout << "Please enter a digit between 0 and 9: "<<  endl;
            cin >> Num;

            switch (Num) {
                  case '3':
                  cout << "The number 3 was entered "      << NumCount << " times. " << endl;

                  case '5':
                  cout << "The number 5 was entered "      << NumCount << " times. " << endl;

                  case '6':
                  cout << "The number 6 was entered "      << NumCount << " times. " << endl;
                  ++Count356;
                  break;
                  }
            }

            while (NumCount<20){
                  ++Num;
                  cout << "Please enter a digit between 0 and 9: "<<  endl;
                  cin >> Num;

                  switch (Num) {
                  case '1':
                  cout << "The number 1 was entered "      << NumCount << " times. " << endl;

                  case '4':
                  cout << "The number 4 was entered "      << NumCount << " times. " << endl;

                  case '9':
                  cout << "The number 9 was entered "      << NumCount << " times. " << endl;
                  ++ Count149;
                  break;
                  }
            }
            return 0;
}



0
 
LVL 22

Expert Comment

by:nietod
ID: 1173866
Now you have two seperate while loops.  One that counts 3,5,6 and one that counts 1,4,9.  This isn't right because the user needs to enter 20 digits and the program should count those 20 digits.  your program has them enter 40 digits (2*20).  If the user entered the same 20 digits twice, the program would work, but that's not a great idea.

You need one loop that works to count both digits.  You will have to modify the switch (case) statement in that loop to make it work.

Now here is a summary of how the switch statement works:  

It looks at the value of the expresssion, in the switch's parenthesis and then looks for the "case" label that has the same value.  When one is found, it starts executing at that point.  That is, it "jumps" to that point skipping over the previous cases.  

Now if no "case" is found that matches, it jumps to the "default" label, if there is one.  If there is no "default" then it jumps to the statement after the "}" that ends the switch statement.  

Now notice that that one weird thing is that when it jums to a "case" (or "default") label it does not execute just the code for that label.  It executes the code from there forward.  So if i wrote a case statment to count vowels like this:

switch (Letter)
{
 case 'a':
   ++A_Cnt;
 case 'e':
   ++E_Cnt;
 case 'i':
   ++I_Cnt;
 case 'o':
   ++O_Cnt;
 case 'u':
   ++U_Cnt;
}

it would not work.  If an "e" were encountered, it would jump to
the line that did "++E_Cnt", which is right.  But after that it would continue down the programing ignoring the "case" statements and executing all the other statements so that "++I_Cnt", "++O_Cnt", and "++U_Cnt" would all execute.  This is not right.  To stop execution at some point, you put in the "break" statement.  This causes the program to jump to the statement after the "}" that ends the switch.  So to fix the vowel case:


switch (Letter)
{
 case 'a':
   ++A_Cnt;
   break;
 case 'e':
   ++E_Cnt;
   break;
 case 'i':
   ++I_Cnt;
   break;
 case 'o':
   ++O_Cnt;
   break;
 case 'u':
   ++U_Cnt;
}

*****************

Now, when you print your results, you do not want to be using "NumCount"  That counts the total number of digits entered.  Thus a line like

"The number 9 was entered " << NumCount << " times. " << endl

will print the number of digits entered (so far), not the number of 9's entered.  In addition, you don't need to report the number of 9's entered, but the number of 1's, 4's, and 9's.  So you should be printing Count149, not NumCount.  

On a related note, do you need a running count?  That is, each time they enter a digit do you want it to print out a count of the number of digits counted.  Because that's what it is doing now.  Typically a program would wait until all 20 digits had been entered and counted before printing out the results.  If you want to wait before printing you need to move the "cout <<" lines from the "switch" statement and put them after the "while" loop.

*****************

One last item.

I guess it was an insult, but it was not directed at you.  But at the students who post questions the night before they are due and that do not admit they are homework assignments all though the OBVIOUSLY are.  (Obvious, because no one ever writes this kinda stuff in a real program.)
0
 

Author Comment

by:snorris3333
ID: 1173867
I suspect I've somehow complicated this problem beyond what the school expects.  On the other hand, the text isn't very clear about how "counters" work at all.  Well, back to it, after some boring but necessary work for a client.

Many thanks again, and I'll get back to you as soon as I work on The Thing from AICS some more.
0
 

Author Comment

by:snorris3333
ID: 1173868
GOT IT.

//Program Q32
//Author:  Stephanie Norris
//Date: 10/16/97

#include <iostream.h>
int main ()
      {
      char       Num;
      const int  ListSize = 20;
      int        Count356 = 0;
      int        Count149 = 0;
      int        NumCount = 0;

      cout << "Please enter " << ListSize << " digits between 0 and 9 and press "
            "the enter key: " << endl;

      while (NumCount <= ListSize){
      cin >> Num;

         switch (Num) {
                  case '3': case '5': case '6':  ++Count356;
                  cout << "The numbers 3, 5, and 6 were entered "      << Count356 << " times. "
                          << endl;
         break;
                  case '1': case '4': case '9': ++Count149;
                  cout << "The numbers 1, 4, and 9 were entered " << Count149 << " times. "
                        << endl;

         break;
         }
            }
            return 0;
}


This gives a running total at the end of the program, rather than a grand total, but I think this is good enough for chapter 4 of Intro C++.  I really appreciate your help.  Your explanations were very clear, and I'm going to print them all out for future reference.  (I also figured out what a REAL student is:  they're those people who sort-of grow up, get jobs, and then throw themselves at my feet on April 15th at 5:20 PM, mumbling things about how their office burned down, and they had to take care of their sick old granny, and....well, you know.)
0
 
LVL 22

Expert Comment

by:nietod
ID: 1173869
Does this mean you have no more questions/problems?  Or are there problems with the code you posted.  (If there are problems, I may be slow in posting a response as I got picked for jury duty this week.)

I think you are confussing REAL students with REAL people.  They are opposites.  (However, opposites attract, at least they did for my wife and me.)
0
 

Author Comment

by:snorris3333
ID: 1173870
The code I posted solves the programming problem, at least on the level I believe is expected of a beginning C++ student.  By that I mean the program runs and answers the question adequately, although not elegantly.  (I don't think Bill Gates is sweating even a little bit).

If that's what REAL people are like, will someone please beam me up?
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now