Functions are NOT fun

buzzard34

Gawd
Joined
Feb 14, 2004
Messages
619
So I have a c++ final coming up next week and I still don't know if I have functions understood. take a look at some examples I made and see if they are correct.

[font=verdana,arial,helvetica]code:[/font]
void name ();
//returns name

int main()
{
name();
return 0;
}

void name()
string name = "buzzard34";
cout << name << endl;
[font=verdana, arial, helvetica]

[/font]
[font=verdana,arial,helvetica]code:[/font]
int SumSquares (int x);
//contains 1 value parameter type int which is
//a 2 digit integer and returns sum of squares of digits of the value thats passed.

int main()
{
stuff
}

int SumSquares(int x)
{
int x,first,second;
cin >> x;
first = x/10;
second = x/10;
return = (sqrt(first)+sqrt(second))
}

example would be like 48; 4^2+8^2=80
[font=verdana, arial, helvetica]

also i have trouble figuring the outputs of some functions like this one:
[/font]
[font=verdana,arial,helvetica]code:[/font]
void figure_me_out (int& a, int& b, int c);

int main()
{
int a,b,c;
a=10;
b=20;
c=30;
figure_me_out(a,b,c);
cout << a << " " << b << " " << c << endl;

a=10;
b=20;
c=30;
figure_me_out(c,a,b);
cout << a << " " << b << " " << c << endl;

a=10;
b=20;
c=30;
figure_me_out(b,b,b)
cout << a << " " << b << " " << c << endl;
return 0;
}

void figure_me_out (int& a, int& b, int c)
{
a=1; b=2; c=3;
}

[font=verdana, arial, helvetica]

what the frink is the output?
Thanks for any help.
[/font]
 
buzzard34 said:
void figure_me_out (int& a, int& b, int c);

int main()
{
int a,b,c;
a=10;
b=20;
c=30;
figure_me_out(a,b,c);
cout << a << " " << b << " " << c << endl;

a=10;
b=20;
c=30;
figure_me_out(c,a,b);
cout << a << " " << b << " " << c << endl;

a=10;
b=20;
c=30;
figure_me_out(b,b,b)
cout << a << " " << b << " " << c << endl;
return 0;
}

void figure_me_out (int& a, int& b, int c)
{
a=1; b=2; c=3;
}

First figure_me_out would result in: 1 2 30
Second Figure me out would result in: 2 20 1
Third one would result in: 10 2 30

Other than that, you have syntax issues with your first and second function examples at the top.
 
Code:
void name ();
//returns name

int main()
{
name();
return 0;
}

void name()
string name = "buzzard34";
cout << name << endl;

Is name() supposed to return a name or just print out a name? If it just prints a name, it's fine, but you need some braces around the body of the name() function.

Code:
int SumSquares (int x);
//contains 1 value parameter type int which is
//a 2 digit integer and returns sum of squares of digits of the value thats passed.

int main()
{
stuff
}

int SumSquares(int x)
{
int x,first,second;
cin >> x;
first = x/10;
second = x/10;
return = (sqrt(first)+sqrt(second))
}

One problem I'm seeing with this code is that you redeclare x inside the function, and you already passed it x. I'm not sure if the C++ compiler even allows for that ( don't think so ).
Also, are you already passing in x or asking for the user to input x within the function? Because right now, you're passing in an x, yet you redeclare x and ask for it to be entered.

Your math is also slightly off.

Code:
first = x/10;
second = x/10;

Both of these expressions nets you the same thing. x is not modified after first=x/10. If you want to break it up into two digits (and assuming you've checked the input to insure it's > 10 and < 100 for two digit positive integers), you could do modulo arithmetic if you know how.

Code:
first = x / 10;
second = x % 10;

So say you have 35. 35 / 10 is 3 because of how C++ handles integer division (returns integer). That's the first digit. Now, x % 10 gets the remainder from dividing a number x into 10. You probably remember this from third grade long division. 35 mod 10 is 5 because 35 goes into 10 3x, and you have 5 remaining.

Also, sqrt is square root. For a simple square just do (first * first) + (second*second). Probably no need to bring <cmath> pow() into this.

also i have trouble figuring the outputs of some functions like this one:
Code:
void figure_me_out (int& a, int& b, int c);

int main()
{
int a,b,c;
a=10;
b=20;
c=30;
figure_me_out(a,b,c);
cout << a << " " << b << " " << c << endl;

a=10;
b=20;
c=30;
figure_me_out(c,a,b);
cout << a << " " << b << " " << c << endl;

a=10;
b=20;
c=30;
figure_me_out(b,b,b)
cout << a << " " << b << " " << c << endl;
return 0;
}

void figure_me_out (int& a, int& b, int c)
{
a=1; b=2; c=3;
}

First one: 1 2 30
Second one: 2 20 1
Third one: 10 2 30

Let's go over this:

Code:
void figure_me_out (int &a, int &b, int c)

You pass this function in 3 values. a and b are passed by reference, and c is passed in by value. You know that passing a variable in by reference means that whatever the function does to modify the variable inside the function, the modification is reflected in the original variable.

Code:
a=10;
b=20;
c=30;
figure_me_out(a,b,c);
cout << a << " " << b << " " << c << endl;

Let's just go over this one.

You pass a, b, c in to figure_me_out.

Inside figure_me_out(int &a, int &b, int c)

The first variable passed in (which was a, value of 30) is modified and it now has a value of 1 inside figure_me_out. Since you passed in by reference, the original 'a' has a value of 1 as well.

Same for b, which is now 2 inside figure_me_out and inside main.

'c', however, is only modified within the scope of figure_me_out. The original c in main() is not changed.

So now print out a, b, c in order and you get:
1 2 30.
 
OK, i semi-understood the explanations. Need a refresher on passing by reference and value though.
 
Passing by value: when you send a variable from one function to another, passing by value means a copy of the value is made for the function being called.

Code:
#include <iostream>

void printX( int x );

int main( )
{
[indent]
int x = 7;
printX(x);
std::cout << x << std::endl;

return 0;
[/indent]
}

void printX( int x )
{
[indent]
x = 12;
std::cout << x << std::endl;
[/indent]
}

What is the output of the above code?
It's
12
7

You passed x by value, so the x inside printX was modified, but that doesn't affect the x in main because a copy was sent.

Pass by reference means you're passing the address of the variable in memory, basically a pointer.

Code:
#include <iostream>

void printX( int [b]&[/b]x );

int main( )
{
[indent]
int x = 7;
printX(x);
std::cout << x << std::endl;

return 0;
[/indent]
}

void printX( int [b]&[/b]x )
{
[indent]
x = 12;
std::cout << x << std::endl;
[/indent]
}

Notice the highlighted &'s. This means that the argument will be passed by reference. Any changes made to a variable passed by reference in a function is reflected in the original function.

So what's the output of this piece of code?
It's
12
12

Because x was modified inside printX and this changes the x in main.

Hope that helps.
 
I've had it. I've really had it. I was working on a final project and I can't figure out how to fix it. Here's where my troubles began.
[font=verdana,arial,helvetica]code:[/font]
int LinSearchID (Grades s[], int size, int target)
//Precondition: s[0],...s[size-1] contains a list of
//objects of type Grades.
//Postcondition: If there is a student with ID target then
//the index of the cell is returned; otherwise, -1 is returned.
{
int index = 0;
bool found = false;
while ((!found) && (index < size))
if (target==s[index])
found = true;
else
index++;
if (found)
return index;
else
return -1;
}



int BinSearchID (Grades s[], int size, int target)
//Precondition: s[0],...s[size-1] contains a list of
//objects of type Grades in student number order
//Postcondition: If there is a student with ID target then
//the index of the cell is returned; otherwise, -1 is returned.
{
int first,last,mid;
while (first <= last)
{
mid = (first+last)/2;
if (s[mid] == target)
return mid;
else if (s[mid] < target)
first = mid+1;
else last = mid-1;
}
return -1;
}
[font=verdana, arial, helvetica]

i also have to figure how to write a function that finds the highest average in a record. No clue where to start, and how to compile it.

still trying to fix the other stuff, giving up because I have other subjects to study for. What. Can. I. Do. To. Understand C++?
[/font]
 
buzzard34 said:
Code:
int LinSearchID (Grades s[], int size, int target)
//Precondition: s[0],...s[size-1] contains a list of 
//objects of type Grades.
//Postcondition: If there is a student with ID target then
//the index of the cell is returned; otherwise, -1 is returned.
{
[indent]
int index = 0;
bool found = false;
while ((!found) && (index < size))
if (target==s[index])
found = true;
else
index++;
if (found)
return index;
else
return -1;
[/indent]
}



int BinSearchID (Grades s[], int size, int target)
//Precondition: s[0],...s[size-1] contains a list of 
//objects of type Grades in student number order
//Postcondition: If there is a student with ID target then
//the index of the cell is returned; otherwise, -1 is returned.
{
[indent]
int first,last,mid;
while (first <= last)
{
      mid = (first+last)/2;
      if (s[mid] == target)
      return mid;
      else if (s[mid] < target)
      first = mid+1;
      else last = mid-1;
}
return -1;
}
[/indent]

i also have to figure how to write a function that finds the highest average in a record. No clue where to start, and how to compile it.

still trying to fix the other stuff, giving up because I have other subjects to study for. What. Can. I. Do. To. Understand C++?

Well, one thing I notice is that you're trying to compare something of type Grade to something of type int. What are the members of the Grade class?

I'll help you as much as I can, but you need to give me some more info with the Grade class.
 
here's the whole program, i dont think theres a class in it unles i'm mistaken:
Code:
 #include <iostream>
 #include <cstdlib>
 #include <fstream>
 #include <iomanip>
 #include "grades.h"
 using namespace std;
 
 const int CLASSSIZE = 250;
 
 
 
 //Function Prototypes
 int LinSearchID (Grades s[], int size, int target);
 //Precondition: s[0],...s[size-1] contains a list of 
 //objects of type Grades.
 //Postcondition: If there is a student with ID target then
 //the index of the cell is returned; otherwise, -1 is returned.
 
 
 int BinSearchID (Grades s[], int size, int target);
 //Precondition: s[0],...s[size-1] contains a list of 
 //objects of type Grades in student number order
 //Postcondition: If there is a student with ID target then
 //the index of the cell is returned; otherwise, -1 is returned.
 
 
 void DisplayAStudent(Grades s);
 //Precondition: s is an object consisting of one student's grades
 //Postcondition: The student's ID and exam scores are displayed.
 
 int FindHighestAverage(Grades s[], int size);
 //Precondition: , s[0],...s[size-1] contain size students records
 //Postcondition: The index a a student with the highest average
 //is returned. s is unchanged. If there is more than one sudent with
 //the highest average - you do not have to find any others.
 
 
 int main()
 {
     ifstream fin;
     int stuNum,score,searchResult,topAverage;
     Grades classRecord[CLASSSIZE];
     int numStudents = 0;
     char filename[16];
     char answer;
     int searchType;
    
  
     cout << "Enter the name of the file containing the class data: \n";
     cin >> filename ;
     fin.open (filename);
     if (fin.fail())
     {
       cout << "Input file opening failed.\n";
       cout << "The program will end now.\n";
       exit(1);
     }
     int index = 0;
     fin  >> stuNum;
 
     while (!fin.eof())
     { 
         classRecord[index].SetStudentNumber(stuNum);
 
     for (int s=1;s < 6; s++)
     {
         fin >> score;
 
         classRecord[index].SetScore(score,s);
     }
     fin >> stuNum;
     index++;
     }
     fin.close();
     
     
     do
     {
       numStudents = index;
       cout << numStudents << endl;
       
       cout << "What Student are you looking for ?\n";
       cin >> stuNum;
       do
       {
         cout << "Do you want to use linear search or binary search ?\n";
         cout << "Remamber to use binary search the file must be sorted.\n";
         cout << "Enter 1 for linear, 2 for binary.\n";
     cin >> searchType;
     switch (searchType)
     {
       case 1: searchResult = LinSearchID (classRecord, index,stuNum);
               break;
       case 2: searchResult = BinSearchID(classRecord, index, stuNum);
               break;
       default: searchResult = 3;
                cout << "Sorry 1 and 2 are the only valid answers.\n";
     }
        }while (searchResult == 3);
 
       if (searchResult == -1)
            cout << "There is no student with that number.\n";
       else
       {
            cout << "This student's record is as follows:\n";
            DisplayAStudent(classRecord[searchResult]);
       } 
       cout << "Do you want to  search for another student ?\n";
       cout << "[Answer Y or y for yes; any other letter for no.\n";
       cin >> answer;
     }while ((answer == 'Y') || (answer == 'y'));
 
    return 0;
 }
 
 
 //Function Implementation Section
 
 void DisplayAStudent(Grades s)
 //Precondition: s is an object consisting of one student's grades
 //Postcondition: The student's ID and exam scores are displayed.
 {
     cout << setw(5) << s.GetStudentNumber();
     for (int k = 1; k <= 5; k++)
     {
       cout << setw(5) << s.GetScore(k);
     }
     cout << endl;
 }
 
 int LinSearchID (Grades s[], int size, int target)
 //Precondition: s[0],...s[size-1] contains a list of 
 //objects of type Grades.
 //Postcondition: If there is a student with ID target then
 //the index of the cell is returned; otherwise, -1 is returned.
 {
 int index = 0;
 bool found = false;
 
 while ((!found) && (index < size))
 {
 if (target==s[index])
 found = true;
 else
 index++;
 }
 if (found)
 return index;
 else
 return -1;
 }
 
 
 
 int BinSearchID (Grades s[], int size, int target)
 //Precondition: s[0],...s[size-1] contains a list of 
 //objects of type Grades in student number order
 //Postcondition: If there is a student with ID target then
 //the index of the cell is returned; otherwise, -1 is returned.
 {
 int first = 0;
 int last = s[size-1];
 int mid;
 
 while (first <= last)
 {
       mid = (first+last)/2;
       if (s[mid] == target)
       return mid;
       else if (s[mid] < target)
       first = mid+1;
       else last = mid-1;
 }
 return -1;
 }
 
 int FindHighestAverage(Grades s[], int size)
 //Precondition: , s[0],...s[size-1] contain size students records
 //Postcondition: The index a a student with the highest average
 //is returned. s is unchanged. If there is more than one sudent with
 //the highest average - you do not have to find any others.
 {
 int highest_grade = 0;
 
 for (int highest_grade = 0; highest_grade <= ; highest_grade++)
 
 
 }
 
Gambit said:
check out the grades.h file ;-)
sorry,
Code:
class Grades
{
  public:
  Grades();
  //Constructor: Sets student number to -999999
  //Sets all 5 scores equal to -1
  
  Grades(int n, int s1, int s2, int s3, int s4, int s5);
  //Constructor: Sets student number to n
  // scores[0] to s1, scores[1] to s2, etc.
  
  void SetScore(int s, int quizNum);
  //Mutator: Sets scores[quizNum-1] to s
  
  void SetStudentNumber(int num);
  //Mutator: Sets stuNumber to num
  
  int GetStudentNumber();
  //Accessor: returns stuNumber
  
  int GetScore (int quizNum);
  //Accessor: returns scores[quizNum - 1] if
  // there is a score, otherwise returns -1.
  
  void OutputScores();
  //Accessor: Displays the student number and all tset
  //scores that have been recorded
  
  double Average();
  // returns the student's average on the quizzes for which
  // there are grades; if no grades have been entered returns -1
  
  
  
  private:
  int stuNumber;
  int scores[5];
  int NumScores();
  
  
};
 
Code:
int LinSearchID (Grades s[], int size, int target)
//Precondition: s[0],...s[size-1] contains a list of 
//objects of type Grades.
//Postcondition: If there is a student with ID target then
//the index of the cell is returned; otherwise, -1 is returned.
{
[indent]
int index = 0;
bool found = false;
while ((!found) && (index < size))
if (target==s[index])
found = true;
else
index++;
if (found)
return index;
else
return -1;
[/indent]
}

Here's your original. Now, I could just give you the answer but you won't learn anything that way.

So this function is just a rather dumb linear search through an array. The array is made up Grade objects. All this you already know.

Now you want to find whether or not there is a Grade object that contains an ID that matches the input 'target' (int target). So what you really want is to compare target to the stuNumber variable of each Grade object inside the array.

Here's my way to do this:

Code:
int LinSearchID (Grades s[], int size, int target)
//Precondition: s[0],...s[size-1] contains a list of 
//objects of type Grades.
//Postcondition: If there is a student with ID target then
//the index of the cell is returned; otherwise, -1 is returned.
{
[indent]for(int index = 0; index < size; ++index)
{[indent]if(s[index].GetStudentNumber() == target) {
[indent]return index;[/indent]
}[/indent]
}
return -1;
[/indent]}

Simple enough eh? You don't need the bool value you had in the original code. Basically if you loop through the array and find it, return the index. After the loop, you know you didn't find it so just return -1.

You could also just loop with a while like while(--size >= 0) and go from there, but eh, for makes it simpler to read.


Now, the second thing:
Code:
int BinSearchID (Grades s[], int size, int target)
//Precondition: s[0],...s[size-1] contains a list of 
//objects of type Grades in student number order
//Postcondition: If there is a student with ID target then
//the index of the cell is returned; otherwise, -1 is returned.
{
[indent]
int first,last,mid;
while (first <= last)
{
      mid = (first+last)/2;
      if (s[mid] == target)
      return mid;
      else if (s[mid] < target)
      first = mid+1;
      else last = mid-1;
}
return -1;
}
[/indent]

Similar to the first one, you want to compare the stuNumber to target.

Code:
if(s[mid].GetStudentNumber() == target) ...



As for the average thing, do you just want to find which Grade object in an array has the highest average?

Okay, basically a simple approach to this is to loop through the array. Use a variable to store the index of the current highest average (GetAverage or whatever function gets average). Keep comparing the current average to the highest average. At the end of the function return the index.

edit: oops nevermind, read description. Also changed typo.
 
BillLeeLee Similar to the first one said:
if(s[mid].GetStudentNumber() == target) ... [/code]



As for the average thing, do you just want to find which Grade object in an array has the highest average?
how do i integrate that line into the function? sorry to sound stupid but i tried various ways but the compiler just gave me the finger. As for the average yes i need to find the highest average. i need a loop for s i guess but I dont know what to implement...:(
I am really upset right now that I will probably get an F in this class because I can't seem to understand what's been going on all semester.
 
buzzard34 said:
how do i integrate that line into the function? sorry to sound stupid but i tried various ways but the compiler just gave me the finger. As for the average yes i need to find the highest average. i need a loop for s i guess but I dont know what to implement...:(
I am really upset right now that I will probably get an F in this class because I can't seem to understand what's been going on all semester.

You want to replace the line highlighted here, because you want to compare Studentnumber, not just s[mid]

Code:
int first,last,mid;
while (first <= last)
{
      mid = (first+last)/2;
      [u][b]if (s[mid] == target)[/b][/u]
      return mid;
      else if (s[mid] < target)
      first = mid+1;
      else last = mid-1;
}
return -1;

And you end up with this:
Code:
int first,last,mid;
while (first <= last)
{
      mid = (first+last)/2;
      [b]if (s[mid].GetStudentNumber() == target)[/b]
      return mid;
      else if (s[mid] < target)
      first = mid+1;
      else last = mid-1;
}
return -1;

As for HighestAverage, here's some pseudo code. Attempt it and see if you can get it. If not post back and I'll try to help again. I don't just want to hand out answers, you should see how much you can do by yourself, it's the best way. ;)

Code:
 int FindHighestAverage(Grades s[], int size);
 //Precondition: , s[0],...s[size-1] contain size students records
 //Postcondition: The index a a student with the highest average
 //is returned. s is unchanged. If there is more than one sudent with
 //the highest average - you do not have to find any others.
{
    // Make an int variable for holding the array index with the Grade that has the highest average. Assign it to index 0.
    int index = 0;

    // Okay, so now you want to loop from 1 to size-1
   for(int i...........blah blah )
    // inside the loop, compare the average of the current Grade object to s[index]'s average. You will have to use the public function from grades.h that returns the Average. That function is, of course, Average().

   // if current object in the loop has a higher average, make that the new index.

   // AFTER LOOP: return index
}

You should probably be able to complete this function in...5 lines.

Hope that helps buddy.
 
Thanks so much for your help, this is what i was able to mix up:
Code:
 {
 int highest_grade = 0;
 for(int index = 0; index < size; ++index)
 {
 	if(s[index].GetStudentNumber() == highest_grade) {
 
 		return 0;
 
 	}
 }
 return -1;
 }

and 5 lines just like you said :D

edit: new problem: It compiles but when i test it it fails to open any documents. How do i fix this??
 
buzzard34 said:
Thanks so much for your help, this is what i was able to mix up:
Code:
{
int highest_grade = 0;
for(int index = 0; index < size; ++index)
{
	if(s[index].GetStudentNumber() == highest_grade) {

		return 0;

	}
}
return -1;
}

and 5 lines just like you said :D


Hehe. Some problems though. You want to compare averages, not student IDs in this case.

Code:
{
int highest_grade = 0;
for(int index = 1; index < size; ++index)
{
	if(s[index].Average() > s[highest_grade].Average()) {
               highest_grade = index;
}
      return highest_grade;
}

edit: new problem: It compiles but when i test it it fails to open any documents. How do i fix this??

It prompts you to enter the filename right? Does the program error out or what? Does the file exist?
 
BillLeeLee said:
Hehe. Some problems though. You want to compare averages, not student IDs in this case.

Code:
 {
 int highest_grade = 0;
 for(int index = 1; index < size; ++index)
 {
 	if(s[index].Average() > s[highest_grade].Average()) {
                highest_grade = index;
 }
       return highest_grade;
 }



It prompts you to enter the filename right? Does the program error out or what? Does the file exist?
originally it said "input file opening failed. Ending program, sorry"
when i redid the last function with the code you so generously provided it worked correctly, i think i made an error previously. Thanks for the help, but I really don't think I'm going to dabble in computer programming for a loooong time. :D
 
Back
Top