mrnutty 761 Senior Poster

Well its school time so some might not have time.

mrnutty 761 Senior Poster

How to use functions :

1) Declare a prototype .

Ex :

//int is the return type
//calculateBonus is the function's name
//int number is its argument
// the semicolon " ; " means its a prototype
int calculateBonus(int number);

2) Give it a body outside of main :

ex :

int calculateBonus(int num)
{
    if( num < 100 ) return 10;
   else if(num < 1000 ) return 100;
   else return 1000;
}

3) Use it inside main :

int main()
{
    int bonus = calculateBonus(100);
  //more code

  return 0;
}

Here is an complete example :

#include<iostream>
using namespace std;

int calculateBonus(int num)
{
    if( num < 100 ) return 10;
   else if(num < 1000 ) return 100;
   else return 1000;
}

int main()
{
   int money = 10;
   int bonus= calculateBonus(money);
   cout<<"bonus = " << bonus << endl;
   return 0;
}
mrnutty 761 Senior Poster

Is there a way to do this without using arrays?

Yep I guess, you can use if statements to sort this.

mrnutty 761 Senior Poster

What have you really learned in the class so far, what concepts?

You haven't learned about functions or you don't want to use functions?

Can you use the standard functions?

Think of all possible ways you can do this before using the minimum of
32 if statements.

mrnutty 761 Senior Poster

I didnt get it 1stperson.. mind to show me..??

In psuedocode of course :

void insertionSort(int * Array, int size)
{
	
	//declare minElem variable to 0

	//for i = 0 to i < size, increment i by 1
	{
		//set minElem to i 
              //for j = i +1 to j < size; increment j by 1
                {
                         //if array[j] is less than array[minElem]
                              //then set minElem to j
                  }
             //now swap array at i with array at minElem
	}
}
mrnutty 761 Senior Poster

well since since there are 5! possible combination, the minimum
number of if stated you will use is 2^5 = 32.

That will suck.

Just use insertion sort, the idea behind it is to mid a max* element
and swap it with the last element. Then repeat it with the last element
decreasing by 1 each time.

mrnutty 761 Senior Poster

Yes, your if/else is incorrect, only 1 of them gets evaluated.

mrnutty 761 Senior Poster

1) use Code tags.

2) The second one. Its more reusable.

mrnutty 761 Senior Poster

but my teacher wants the user to be able to be able to input a number of [B]any [/B]length

That means that you shouldn't use int, double , long long or whatever.
It means you should get your input as a string in order to have any length.
Primitive data types have limits on the max and min range of number
they can represent, but my teacher wants the user to be able to
be able to input a number of any length"]More Info on that.

mrnutty 761 Senior Poster

Also, if the numbers aren't too far apart, then what you could do
is get the average of the 3 numbers, and find the number that is closest
to the average. This will work long as the number aren't too far apart, like
1,2,100;

for example if the input was 1,2,3 and you know that the median is 2,
but if you found the average, totalSum/totalElement = (3+2+1)/3 = 6/3 = 2, then you see that this also gets the correct answer. Use it at your
own risk.

mrnutty 761 Senior Poster

in your reverse function, what happens if num is less than 0?
What would the function return?

Get the input as a string and print the string backwards. Makes sure the string contains numeric data if you want.

mrnutty 761 Senior Poster

Have a test condition in your for loop.

In psuedocode :

for i = 0 untill MAX{
pick1 = random number
pick2 = random number
while(pick2 == pick1 ) pick2 = another random number
pick3 = random number
while(pick3 == pick2 or pick3 == pick1) pick3 = another random number
}
mrnutty 761 Senior Poster

They have given you the answer, but let me expand on that :

Your prototype for fillArray is this :

int   fillArray(int);//Trying to make a fn that fills an array

What does that mean ? It says that fillArray takes an int variable and
returns an int variable. What you want it to say is that fillArray
takes a int array, and a int variable and returns nothing.

So it would be something like this :

void  fillArray(int anArray[], int itsSize);

Again, that means that fillArray takes an int array and its size as a
variable. Then all you have to do is make sure its defined.

mrnutty 761 Senior Poster

1) Why ?

2) need compile time variable meaning there will be a fixed amount
of inputs to get

3) Need to implement your own sorting method and use it inside main,
so technically it won't be a function. If not then you will need a lot
of if/else or you can use trees.

4) Bad Idea.

mrnutty 761 Senior Poster

Think of main as a variable. And your function takes a variable a well.
But the variable is not normal, its a function. A function can be passed to another function like a variable. You just need proper prototype.

Compare :

void Foo(int var); //takes in a int variable
void Foo2( int(*pF)() ); //takes in a int function with no parameters

You can also use typedef to make the function pointer look more
natural.

mrnutty 761 Senior Poster

First initialize your variables.

Average = totalSum/totalElement.

Thus totalSum should be computed first and then divide it by the
array size.

mrnutty 761 Senior Poster

How about you warp your code into code tags, correctly.

Then comment on each line of code, so we can see what you are thinking.

mrnutty 761 Senior Poster

Input = cin
x is a float
y is a int
r is a int

for i to y means :

for(int i = 1; i < y; i++)
{
   //code goes here
}

The "code goes here" part is result = result * i;

mrnutty 761 Senior Poster

Here is a hint :

********** 10 stars
*********  9 stars
********   8 stars 
*******   7 stars
******  6 stars
***** 5 stars
**** 4 stars
***  3 stars
** 2 stars
* 1 stars
**  2 stars
*** 3 stars
**** 
*****
******
*******
********
*********
********** 10 stars

So you see that they decrease by 1 star until they reach 1 then they
start increment.

so assuming you can separate this problem into 2 blocks, you can
do something like this :

for(int i = 10; i != 1; i--)
     printStars(i); //a function that prints i stars with endl
for(int i = 2; i <= 10; i++)
     printStars(i);

Now what should your printStars look like :
for example if one calls printStars(4) it should output the following :

****

Go ahead and try to devise printStars then you problem becomes much
easier.

mrnutty 761 Senior Poster

Use the suggestion above, although you might want to google sorting for knowledge experience.

You can do this if you want to use std::sort;

#
int main()
{
int x[5];
prompt(x);
printreverse(x);
std::sort(x,x+5);
system("pause");
return 0;
}
mrnutty 761 Senior Poster

>>i not sure what is the single quote means...

Its usually used with char variables :

char quit = 'n'; 
if( quit == 'n' ) 
   cout<<"Still playing\n";
mrnutty 761 Senior Poster

You forgot to enable GL_COLOR_MATERIAL, when using lighting. I
changed it a little, take a look at the comments.

#define GLUT_DISABLE_ATEXIT_HACK
#include <stdlib.h>
#include <GL/glut.h>


// Globals
void display();
void myInit();
//Set up material
	GLfloat no_mat[] = { 0.0, 0.0, 0.0, 1.0 };
	GLfloat mat_ambient[] = { 0.7, 0.7, 0.7, 1.0 };
	GLfloat mat_ambient_color[] = { 1,1,1,1 };
	GLfloat mat_diffuse[] = { 0.1, 0.5, 0.8, 1.0 };
	GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
	GLfloat no_shininess[] = { 0.0 };
	GLfloat low_shininess[] = { 5.0 };
	GLfloat high_shininess[] = { 100.0 };
	GLfloat mat_emission[] = {1,1,1,1};

//Set up lighting
	GLfloat light0_pos[]={20.0, 100.0, 1.0, 0.0};
	
	GLfloat diffuse0[]={1.0,1.0, 1.0, 1.0};
	GLfloat ambient0[]={0.4, 1.0, 1.0, 1.0};
	GLfloat specular0[]={1.0, 1.0, 1.0, 1.0};

	GLfloat ambient[] = { 0.2, 0.2, 0.2, 1.0 };
   GLfloat diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
   GLfloat specular[] = { 1.0, 1.0, 1.0, 1.0 };
   GLfloat position[] = { 0.0, 3.0, 2.0, 0.0 };
   GLfloat lmodel_ambient[] = { 0.4, 0.4, 0.4, 1.0 };
   GLfloat local_view[] = { 0.0 };
   GLfloat global_ambient[]={0,0,0,0};

void myReshape(int w, int h);
void drawSphere();
GLsizei wh=800, ww=800;

void myInit()
{
  
   glClearColor(0.7f, 0.9f, 1.0f, 1.0f);	// Set background color to sky blue.
   glEnable(GL_DEPTH_TEST);
   glShadeModel(GL_SMOOTH);

   glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
   glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
   glLightfv(GL_LIGHT0, GL_POSITION, position);

   glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
   glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, local_view);

   glEnable(GL_LIGHTING);
   glEnable(GL_LIGHT0);
   glEnable(GL_NORMALIZE);	
	//NEW
   glEnable(GL_COLOR_MATERIAL);

  glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
  glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
  glMaterialfv(GL_FRONT, GL_SPECULAR, mat_ambient);
  glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
  glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
}


void display(void)
{	
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();

//Draw sphere
   glPushMatrix();
   glTranslatef (-4.0, 5.0, 0.0);
   glColor3f(1.0f,1.0f,0.0f); …
mrnutty 761 Senior Poster

wanna send me the file so I can take a look at it. Make sure you
have enabled lighting and LIGHT0

mrnutty 761 Senior Poster

Ah, ok. I tried this...but it still doesn't work:

......
	if(info == 'c')
	{
		gauge[0]='C';
		gauge[1]='F';
		values(float value1[11]);
		for(int x=0;x<=10;x++)
			value2[x]=(value1[x]*9)/5+32;
	}
	else
	{
		gauge[0] = 'F';
		gauge[1] = 'C';
		values(float value1[11]);
		for(int x=0;x<=10;x++)
			value2[x] = ((value1[x] - 32) * 5)/9;
	}
...............

your function call should be :

values(value1);
mrnutty 761 Senior Poster

The simplest way to adjust the range of rand() is with the modulus operator:

#include <iostream>
#include <cstdlib>

int main()
{
    for (int x = 0; x < 20; ++x)
    {
        std::cout << (std::rand() % 900 + 100) << '\n';
    }
}

I am sure someone will chime in with the multitude of problems that this solution has, but if you need to worry about those problems, rand() is not the right random number generator for your application. :)

Forgot to seed.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
    srand(time(0)); 

    for (int x = 0; x < 20; ++x)
    {
        std::cout << (std::rand() % 900 + 100) << '\n';
    }
}
mrnutty 761 Senior Poster

Did you call glNormalize in your init function ?

By having proper normals the light "reflects" of the shape and thus it works out as planned. If you don't calculate normals then your object
feels the effect of ambient lighting, thus looks dark (in most case).

Try this :

glBegin(GL_POLYGON);
           glNormal(0.0f,0.0f,1.0f);
		glVertex3d(-8,-8,0);
		glVertex3d(8,-8,0);
		glVertex3d(8,-2,0);
		glVertex3d(-8,-2,0);
	glEnd();
mrnutty 761 Senior Poster

Its because you don't have your normals calculated for rectangles.
Plus put your lighting function in our initGL function.

mrnutty 761 Senior Poster

You get seg fault. because your overflowing stack.

It seems that you want a number ranging from 0.1 to 0.999

Look here

mrnutty 761 Senior Poster

You need to set the stream flags, look below :

cout<<fixed; //make it so that 3.000 comes out instead of 3
	cout.precision(2); // make it so that 3.00 comes out

Now when you print something like cout << GPA << endl; and if GPA is a whole number (0,1,2,3,4) then it will print
it out like 0.00,1.00,2.00,3.00,4.00.

Put that code before you print out the GPA.

mrnutty 761 Senior Poster

Hven't tried it out and its about 3 am but I'll give it a shot :

I will build up :

CASE A : First to create a 1d array :

const int NODE_SIZE = 5;
Node * p = new Node[NODE_SIZE];

CASE B : Now to create a 2 d array you need to have each of the node
element carry some more node element.

const int NODE_X = 5;
const int NODE_Y = 5;
Node **p = new Node*[NODE_X];

//each node_x needs its own node y to create a 5x5 2d array
for(int i = 0; i < NODE_X; i++){
        p[i] = new Node[NODE_Y]

CASE C: //For a 3d array each node has to has NODE_Y element and each
NODE_Y element has to have its NODE_Z element

const int NODE_X = 5;
	const int NODE_Y = 5;
	const int NODE_Z = 5;
	
	//currentl 1d array
	Node*** p = new Node**[NODE_X];
	//now a 2d array
	for(int i = 0; i < NODE_X; i++){
		p[i] = new Node*[NODE_Y];		
	}
	//now a 3d array
	for(int i = 0; i < NODE_Y; i++)
	{
		for(int j = 0; j < NODE_Y; j++){
			p[i][j] = new Node[NODE_Z];
		}
	}

For case A ( 1 D array ) you can access and write data like this :
Node = ...

For case B (2d array) you can access and write data like this :
Node[j] = ...

For case C( 3d array) you …

mrnutty 761 Senior Poster

In your first post you haven't defined a name within scope. I think what
you are trying to is something like this :

#include<iostream>
#include<string>
using namespace std;

class Test
{
    string name;
    public :
     Test(string str) { name = str; }
     Test() { name = "NULL"; }
     void setName(string str) { name = str; }
     string getName() { return name; }   
};

int main()
{
    Test test1("Greatest 4 eva");
    cout << test1.getName();
    test1.setName("4 eva the greatest");
    cout << test1.getName();
  return 0;
}
mrnutty 761 Senior Poster

>>Hi there,
Hello there.

>>I am new in java and some basic help would be appreciated. e.g
Ok lets see...

>>1-What's the out put of;
>>double number = (1/3)*3;
>>System.out.println("(1/3)*3 is equal to " + number);
>>What's missing?
Did you try this out on a compiler ? Is this a H.W question ?
Here is a hint : in programming , 1/3 != 0.333...

>>2- Convert each of the following mathematical formula to java >>expression;

>>3x and 3x+y
More hints :
Declare a variable x ;
Declare a variable result1 and result2 and a variable y
For result1 make it equal to 3 time the variable x
For result2 make it equal to result1 plus 3

>>Thank you in advance
Hope that helped. Next time show some effort.

mrnutty 761 Senior Poster

1)Draw the top border
2)Draw the first '*' and follow it up with space
3)Repeat 2 until end
4) Draw the bottom border

Maybe this will help :

void drawB()
{
     const int C = 4;
     const int R = 4;

      for(int i = 0; i < R; i++)
     {
          for(int j = 0; j < C; j++)
           {
               cout<<"*";
            }
            cout<endl;
      }
    
      
}

So you know the code above draws :
* * * *
* * * *
* * * *

what you need inside the second for loop is a if/else statement.
But what will be the condition ?
Well from the picture we can see that Row 1 and Row 4 needs all the star, i.e i = 0 && i = 3 and in the middle we see that when j = 0 we need
a star, and the we need spaces until j = 3.
putting all these together we get something like this :

//inside the second for loop
  if( i == 0 || i == 3 ) /*print stars */
  else if(j == 0 || j == 3 ) /* print start */
  else /*print spaces */

So here is what the result might look like in java :

for(int i = 0; i < 4; i++){
            for(int j = 0; j < 4; j++){
                if( i == 0 || i == 3)
                    System.out.print("*");
                else if(j == 0 || j == 3)
                    System.out.print("*");
                else System.out.print(" ");
            }
            System.out.println();
        }
mrnutty 761 Senior Poster

well it should have a break statement there but, when isPrime is set
to false in the loop, no matter what it will come out as false because its not being set true inside the loop, its only being set to false. So it wouldn't matter after it finds its first factor.

mrnutty 761 Senior Poster

Look up the definition of a prime number, and you will see that
it is a number that can only be divisible evenly by itself and 1.

For example , 3 is a prime number because 3 can only be divided by its
self(3) and 1, without having any remainder left over,
3/3 = 1 remainder 0
3/2 is a decimal number
3/1 = 1 which is a whole number, with remainder 0

Now lets see what the loop does :

for(i=1; i<=100; i++) //starts from 1 to 100, i is used as the number to see if its prime
  {
    isprime = true; //say i is a prime for now
 
    // see if the number is evenly divisible
    for(j=2; j<=i/2; j++) // j starts from 2 to i/2 because every number above i/2 is divisible by i 
    // if is is, it is not prime
    if((i%j) == 0) isprime = false; //check is evenly divisible any other number, i.e check if i / j = a whole number, if so then it is a not a prime
 
    if(isprime)
     cout << i << " is prime.\n"
  }

Read up on prime then you will get this algo.

mrnutty 761 Senior Poster

There are other alternatives like boost shared_ptr where
more than 1 pointer can have reference to an object.

I assume Node is a class or a struct, so have the user pass in
a Node *[MAP_WIDTH][MAP_HEIGHT] and from there you can copy the
original content onto the array that passed on, note what you are trying
to do might be expensive depending on the size of you 3d array.

mrnutty 761 Senior Poster

oh, didn't see you need to round off to 2 decimal places....

setpricision is the way to go then.

No, not really, if the OP wants the value to be rounded to 2 decimal
places then he needs to convert that value into a two decimal
placed value, setprecision just output(i.e makes it appear) the final
value as rounded to 2 decimal place.

Maybe this will help;
//Its not perfectly precise

float myConvert(float num){
	return  ( int(num*100)/100.0f );
}
mrnutty 761 Senior Poster

or you can just make your own function :

int round(float num){	
	return (int)(num+0.5);
}
int roundDown(float num){
	return (int)(num);
}

example output :

Enter a number : 3.14
Round = 3
roundDown = 3

Enter a number : 3.5
Round = 4
roundDown = 3

For negative values you will have to do a little more, but I don't think
GPA should be negative, so there is no need.

mrnutty 761 Senior Poster

How about dynamically allocating your Node, then your return type
can be of Node***.

Alternative, you can use 3d vectors and have the return types as 3d
vectors as well.

mrnutty 761 Senior Poster

did you try <ctime>

mrnutty 761 Senior Poster

At this stage(I am assuming), it may be easier( for you) to create a function, like so :

class Timer
{
    int h,m,s;
    public :
     void getTime() { cin >> h >> m >> s; }
}
mrnutty 761 Senior Poster

where is the position of the box relative to ? Its center ? Edge ?

mrnutty 761 Senior Poster

hint :

int x = 0, y = 0;
int t = x + y;

is not the same as

int x, y;
int t = x + y
mrnutty 761 Senior Poster

v1 an v2 represent vectors, so if v1 = <i,j,k> and v2 = <i,j,k> then
the distance between them is (v1 - v2).length.

Remember the length is the magnitude of the vector.

mrnutty 761 Senior Poster

print out the sum, cout<<sum << endl;

mrnutty 761 Senior Poster

This is problematice :

int sum = 0;
int x=0; //  you declared it inside the for loop below
		for(int x=0; x<3; x++);
		{
			x=x+sum; //what happened to num array?
			cout << "The total is: ";
			cin >> x;
		}

change to :

int sum = 0;
		for(int x=0; x<3; x++);
                     sum = sum + num[x];

		cout << "The total is: " << x << endl;
mrnutty 761 Senior Poster

The distance between two vector is given by (v1-v2).length();
Your return type should be similar to the parameters passed.

And welcome!

mrnutty 761 Senior Poster

If thats your case then you should declare a pure virtual function like so :

virtual string getName() = 0;

That means that this class is a ABC class and all subclass should
redefine the method getName().

mrnutty 761 Senior Poster

Thanks for helping me out firstPerson !

Can I ask though, I see the base class in your example has a datamember called 'name'.

My base class however is an abstract base class.

Should I add a datamember to my base class even though it won't ever be used?

You should not add data variables to Abstract Base class(ABC) if it wont be used in its subclass.

mrnutty 761 Senior Poster

>>I'm storing base class pointers in a vector, the pointers are pointing to objects from the derived class ( Leads ).
>>I'm unable to access the 'getter' functions of the derived class. How can this be done?

It seems like you need the use of virtual functions. The error message says what it means, you have not defined a getDate function in you
base class.

Here is an example of something that might help you :

#include <iostream>
#include <vector>
#include<string>

using namespace std;


class Base{
private :
	string name;
public:
	Base() : name("") { };
	Base(const string str) : name(str) { };

	virtual const string getName() {
		return name;
	}
};

class Derived : public Base{
	string myName;
public:
	Derived() : Base(), myName("") { }
	Derived(const string derStr) : myName(derStr) { }
	Derived(const string baseStr, const string derStr) : Base(baseStr) , myName(derStr) { }
	const string getName() {
		return myName;
	}
};
int main()
{  
	vector<Base*> baseVec;	
	Base b1("base 1");
	Derived d1("derived 1");
	Derived d2("derived 2");

	baseVec.push_back( &b1);
	baseVec.push_back( &d1);
	baseVec.push_back( &d2);

	for(unsigned int i = 0; i < baseVec.size(); i++){
		cout << baseVec[i]->getName() << endl;
	}
	return 0;
}
Carrots commented: Thanks ever so much buddy! :) +1