dusktreader 137 Posting Whiz in Training

<cracking knuckles>
Ok, let's dig into this.

As I understand your problem is to minimize this highly nested loop which print the value of 12 variable.

You should note that the program calls two functions a() and b() . So, it is doing more than just printing out the values of variables. At any rate, yes, this seems to be the main push of the program.

Here is my very short program for that but very deep logic is behind that please try to understand the logic behind this first take look too code

1. Program isn't that short
2. Logic isn't that deep
3. Maybe you should present your algorithm in clearer terms instead of slapping the reader with convoluted pure C code and expecting them to follow

long double n_digit= 5;//0,1,2
long double n_var =4;//x,y,z
long double dif_com =pow( n_digit,n_var);

When I got here, I knew we were in for a doozy. I notice that you are calculating the number all possible combination of n-digit numbers in a b-based numbering system. First of all, this is not necessary. Secondly, it is wrong. Let's investigate why

First look at a section of the OP's code:

for(int i=5;i>0;i--)
  {
    for(int j=5;j>0;j--)
    {
    if(j<=i){

We can see clearly that the nested logic within the for loop iterating j is only executed when j is less than or equal to i. This logic is repeated for each loop. Obviously, then, we aren't interested in every …

Akill10 commented: well said! +1
dusktreader 137 Posting Whiz in Training

I forgot to mention that you use the above code for your application by subsituting an array (or vector, etc) of ints for the loop control variables. So:

i  j  k ... t
  |  |  |     |
  v  v  v     v
[ 4  4  4 ... 2 ]
dusktreader 137 Posting Whiz in Training

@firstPerson
That is a great idea for engineering students. I don't know if I'm convinced that it's appropriate for CS students ( because I friggen' hate matlab ).

I really think a dynamic programming language should be taught in CS I. This way, the basics of programming can be clearly taught without all the clutter of low-level maintenance to sour students to the art. Being a fan, I think Python would be a great language for anyone to cut their programming teeth on.

dusktreader 137 Posting Whiz in Training

What it appears to me is that you have a specialized base-5 numbering system. It is specialized in that it has rules that dictate how you count down in this system. You could make this system very extensible and have it work with an arbitrary number of digits and arbitrary numerical base. The best way to do this is to develop some rules:

* A number in this system may have an arbitrary numerical base b
* A number in this system may have an arbitrary number of digits n
* No digit at index i in the number may be larger than the digit at index i-1


I have implemented a system like this before. I had to create my own specialized numbering system for this problem: http://www.daniweb.com/forums/thread280248.html
Your challenge is similar.

Try implementing something like this:

b = 5                      # 5 is arbitrarily chosen.  this could be any number
n = 24                     # again, 24 is arbitrary
num = array[n]
for i from 0 to n:
    num[i] = b - 1         # Set all numerals to b-1

while num[0] > 0:          # Terminate when the leftmost digit is 0.
    do something with num  # All the rest of the code is counting down
    j = n - 1
    num[j] -= 1            # Decrement the right-most digit
    while num[j] < 0:      # If the digit goes below 0, you have to decrement the digit to the left
        j …
dusktreader 137 Posting Whiz in Training

@OP

I see no reason for the Die object to store the result of its roll. There is nothing wrong with this idea. However, it seems that you will always first roll the die and then fetch its value. This could be accomplished in one step by having the roll() function return the result of the roll. You could still store the result, if you really wanted to, and fetch it again later with the getFace() function:

int Die::Roll()
{
    face = rand() % 6 + 1;
    return face;	
}

int Die::getFace()
{
    return face;
}

if you don't need to store the result (i.e. you will use it right away):

int Die::Roll()
{
    return rand() % 6 + 1;
}

The DiceRoll::rollDice() and DiceRoll::getRollFaces() could be consolidated in the same way.

Fbody commented: Both good points, but please see response. +2
dusktreader 137 Posting Whiz in Training

Die::Die() //Initializes Face data member
{
Face = 1,2,3,4,5,6;
}

I am not sure what you wanted to achieve by this, but this assigns 6 to Face. The operator comma works like this - it evaluates all of its arguments from left to right then returns the rightmost argument, in this case 6. So, this is one thing.

This is not quite correct. The comma operator ( http://msdn.microsoft.com/en-us/library/zs06xbxh%28VS.80%29.aspx -> please forgive the microsoft link. It seemed to be the most informative that I could find quickly ) is indeed evaluated from left to right. It also returns the right-most argument. However, you need to remember to check operator precedence. The comma operator allows two statements to be processed in one line of code. It gurantees that the left statement is completed from before the right, and that all the side-effects of the left statement will influence the right statement.

In this case, the assignment operator has a higher precedence than the comma operator, so it is evaluated first. So, Face is set to 1; The following statements are constant integer expressions that have no effect. The line does indeed return 6, but nothing is done with that value, so it is ignored.

Now, if the line read:

Face = ( Face = 1,2,3,4,5,6 );

Face would first be assigned to 1, then all of the constant expressions would be evaluated, then 6 would be returned from the last comma operator and Face …

dusktreader 137 Posting Whiz in Training

@firstPerson & Fbody

I couldn't agree more. However, I have known many professors ( teachers and colleagues ) that recommend against using the STL even outside/after the classroom. I think I has a lot to do with the stubbornness of C programmers to accept a new paradigm.

Usually, Computer Science programs progress something like:

Computer Science I - Introduction to Computer Science (required of engineers also)
Computer Science II - Language specific tools and basic algorithms
Data Structures - Study of data composition, iterative processing, and intermediate algorithms

I think it is quite unfortunate that in CS I professors put introductory students through the pain of managing arrays. I work with engineers and scientists that have their entire programming knowledge based upon one college class. Every time I see them declare a static array of structs 1000 items deep, I rue the day their professor told them to use this in CS I:

myStruct myArray[1000];
int    myArrayCounter = 0;
dusktreader 137 Posting Whiz in Training

My school for a lot of reasons frowns on the STL. In fact they barely teach it. I understand some of their concerns, but at the same time the STL doesn't have cooties :D.

This is, unfortunately, quite common. I really don't understand this mentality. The STL is a standard library, so it ships with all c++ compilers. It is a stable library, and, if you use it as it was intended (i.e. don't use it with threads), it is a very useful and powerful tool.

Sadly, a lot of professors of Computer Science still cling desperately to a lot of conventions they studied as students of the C programming language. In those days, you spent a lot of time and effort managing memory and array sizes.

There are many times when the STL is not appropriate for the task. However, for most general purpose container needs, the STL is great. I'm a feisty person, so I would question my professor as to why, specifically, he doesn't teach the STL.

Here are a few neat points about STL containers:

1. STL vectors have the same time complexity as arrays for random access.
2. STL lists have the same time complexity for insertion/deletion as a self-implemented linked list.
3. STL is a standard with historic stability.
4. STL containers use dynamic memory allocation and de-allocation internally.
5. STL containers are easy to use and richly featured.
6. STL containers use a common …

dusktreader 137 Posting Whiz in Training

I still disagree.

If you make the equality operator a member, it is somewhere between difficult and impossible in general to avoid situations in which a==b compiles but b==a doesn't.

Making it a non-member destroys inheritance. If you want to virtualize equality operators, they need to be members. In regards to the == symmetry. I generally don't support writing equality functions that take differently typed arguments for the left and right side. Semantically, an object of type A should never be equivalent to an object of type B. If the equality of underlying data needs to be tested, or if you need to test functional equivalence, you should use explicit conversion/extraction functions in your equality logical expression. Alternatively, you could provide implicit conversion by specialized constructors.

IntegerObject A( 3 );
    RealObject B( 3.0 );
    
    A == B;    // Should only be valid if IntegerObject has
               // a constructor from a RealObject.  otherwise

    A == B.toInt();  // I prefer this approach.  Explicitness is nice, and
                     // there is symmetry in the equivalence arguments

My main point here is that the underlying semantics of an equivalence test expect that the type of left and right side arguments must be the same. I.E. An apple cannot equal an orange, even if they are the same size.

dusktreader 137 Posting Whiz in Training

Hmmm.... I see the problem. How asinine to make the bitset size controlled by a template parameter.

I think you could go down two roads.

First, you could store your bits in the string exclusively and return a specific bitset when asked:

template <int bsize>
bitset<bsize> getBits()
{
    return bitset<bsize> bits( s );
}

I would personally favor using a vector<bool>. Of course, you'll have to implement your own logic. This would provide all the extensibility you would need.

dusktreader 137 Posting Whiz in Training

I think the best way to achieve this is to wrap the functionality of a bitset with custom functions.

So, to extend your bitset:

class TryBits
{
// whatever other functionality
public:
    extend( const string& ns )
    {
        // insert a check for ns to be a valid bit string.
        //  i.e. only 1s and 0s
        s += ns;
        b = bitset< s.size() >( s );
    }
    append( bool nbit )
    {
        bitset< b.count() + 1 > nb;
        for( int i=0; i<b.count(); i++ )
            nb[i] = b[i];
        nb[ b.count() ] = nbit;
        b = nb;
    }
    void remove( int index )
    {
        // check boundary conditions     
        bitset< b.count() - 1 > nb;
        for( int i=0, j=0; i<b.count(); i++, j++ )
        {
            if( i == index )
                i++;
            nb[j] = b[i];
        }
        b = nb;
    }
};

I haven't tested any of this, but I think you could proceed with this kind of an idea. You would probably want to add in a setSize( int n ) function as well.

dusktreader 137 Posting Whiz in Training

I hadn't noticed it before, but in general, defining symmetrical operators such as == as members is the road to madness. If you want them to have virtual properties, you should do something like this:

bool operator==(const Foo& a, const Foo& b)
{
    return a.equal(b);
}

and now you can define equal to do whatever typechecking you need on the type of b (noting that the type of a already determines which version of equal will be called).

I partly agree.

I think the equality operator should be a member function of the class it will be operating on. Otherwise, it will have to be a friend function, which I avoid unless necessary. Furthermore, by making it a member function, you may also make it virtual, which I recommend.

Now, let's talk about the part I agree with! I also support making explicit, non operator member functions in the class that are used by the operators. I generally think of operator overloading as a convenience for any segment of code that externally manipulates an object. Within the class, however, I prefer using explicit functions.

Here's an example of how I typically implement this sort of functionality:

class Base
{
private:
    int b;
public:
    Base() : b(0){}
    Base( int b ) : b(b){}
    virtual ~Base(){}
    
    virtual bool equal( const Base& other ) const
    {
        return b == other.b;
    }
    virtual bool operator==( const Base& other ) const
    {
        return equal( other );
    }
};

class Derived
{
private: …
dusktreader 137 Posting Whiz in Training

seems to give correct answer but just looks wrong to me

It is wrong. GCD algorithm is looking for multiplicative factors. So, subtraction is not the right method here. If you are getting correct results, I think it is coincidental. Read my first response. You need to use modulus.

dusktreader 137 Posting Whiz in Training

You are returning the result of the function call. This is basically forwarding the result of the function at a lower level to the call at a higher level.

Think about this simple recursive function:

function sum_dum( number ):
    if number == 0:  # This is the base case
        return 0
    else:
        return 1 + sum_dum( number -1 )  # This is the recursive call

Now, let's see how it works:

main program scope:
-------------------
  number = 4
  print sum_dum( number ) -> passes off to number to first recursion level

---------------------
first recursion level
---------------------
  number == 4
  number != 0
  return 1 + result of second recursion level on number -1

----------------------
second recursion level
----------------------
  number == 3
  number != 0
  return 1 + result of third recursion level on number -1

---------------------
third recursion level
---------------------
  number == 2
  number != 0
  return 1 + result of fourth recursion level on number -1

----------------------
fourth recursion level
----------------------
  number == 1
  number != 0
  return 1 + result of fifth recursion level on number -1

---------------------
fifth recursion level
---------------------
  number == 0  <----- Aha!  The base case
  return 0

----------------------
fourth recursion level
----------------------
  return 1 + 0  <- result of fifth level

---------------------
third recursion level
---------------------
  return 1 + 1  <- result of fourth level

---------------------
second recursion level
---------------------
  return 1 + 2  <- result of third level

---------------------
first recursion level
---------------------
  return 1 + 3  <- result …
dusktreader 137 Posting Whiz in Training

You have a few problems:
1. This is a recusion problem, but you are not recursing correctly:

int g_c_d(int a,int b)
{
    int c;
    c=abs(b-a);
    cout<<a<<" "<<b<<" "<<c<<endl;/*put this in to check it was going ok*/
    if(c==0){return a;}
    if(b>a){b=a;}
    a=c;
    g_c_d(a,b); [B]// This value should be returned[/B]
}

2. You aren't implementing the algorithm correctly. This algorithm is looking for multiplicative factors, so you will need to do some division (by modulus):

This is the recursive Euclidean Algorithm for GCD in pseudocode:

function gcd( a, b ):
    if b = 0
       return a
    else
       return gcd( b, a mod b )

Try to implement this, and let us know how it goes.

dusktreader 137 Posting Whiz in Training

say iter1 and iter2 are both iterators

*iter1++=*iter2++;

what does this line means? Can anybody help explain? ++ and * which is done first?
thanks

Here's a page that will be very helpful!

Operator precedence in c++ is important, but I prefer explicit code to implicit trickery. Parentheses are your friend, and they make sure that your logic is plain. In this case the post-increment operator is evaluated before the dereference. Try this code first to see how this works:

#include <iostream>

using namespace std;

int main()
{
    int arr[4] = { 2, 3, 5, 7 };
    int* ptr = arr + 1;
    *ptr++;
    cout << *ptr << endl;
    return 0;
}

output:

2,3,5,7,
5

Even though I am using pointers here, the logic is the same.
Here's what's happening:
Line 8: ptr references the second value of the array == 3
Line 9, part 1: Post-increment is evaluated. This means the pointer will be incremented, but the increment will happen after this line of code is executed. So, the pointer will still refer to the second element of the array for this line
Line 9, part 2: The pointer is dereferenced. However, nothing else happens here, so...boring.
Line 10,11: Output the values of the array
Line 12: Output the value of the element to which the pointer refers. Since, between line 9 and line 10 the pointer was incremented, it now points to the third value of the …

dusktreader 137 Posting Whiz in Training

Yes, this code is broken. First, receive is not declared in the main function. You must first declare an object of type bank. Secondly, you won't be able to use strcpy to write data directly into the c-string bank::receive unless you make a dangerous assumption. Most compilers place the private members of a class at the very beginning of the objects allocated memory. It is often possible to access this privare memory by reading or writing data directly from the memory address of the object. I don't think this sort of allocation is in the c++ spec, however, so I think this sort of hack can result in undefined behavior.

I'd like to point out that you can make your class much more user friendly by adding some functionality. First, you could make your bank constructor take a static character array as an argument to instantiate its receive c-string:

class bank
{
protected:
    char receive[20];
public:
    bank( const char* recStr ); // Implement this to copy recStr into receive
};

Secondly, you could write a function in bank called write that knows how to write its data to a binary ostream:

class bank
{
protected:
    char receive[20];
public:
    bank( const char* recStr ); // Implement this to copy recStr into receive
    write( ostream& out );  // Implement this to write receive to the ostream
};

I also must make one strong suggestion. Since you are using the c++ Standard Template Library already by utilizing fstream, you should …

dusktreader 137 Posting Whiz in Training

This is unnecessary code:

bool Candidate::operator ==(const Candidate& right) const
{
    //return (firstName == right.firstName && lastName == right.lastName);
    // Rather than the above, I used this...
    return (static_cast<Person>(*this) == static_cast<Person>(right));
}

If you do not define this operator in your derived Candidate class, the operator function from your base Person class will be used. I think you need to work on the concepts of inheritance a little bit.

Consider this:

#include <iostream>

using namespace std;

class Base
{
    int value;
public:
    Base( int value ) : value(value){}
    bool operator==( const Base& other )
    {
        return value == other.value;
    }
};

class Derived : public Base
{
public:
    Derived( int value ) : Base(value){}
};

int main()
{
    Base b0( 4 );
    Derived d0( 2 * 2 );
    Derived d1( 2 + 2 );
    cout << ( b0 == d0 ) << endl;
    cout << ( b0 == d1 ) << endl;
    cout << ( d0 == d1 ) << endl;
    return 0;
}

If you can understand why this works, you are on your way.

dusktreader 137 Posting Whiz in Training

Perhaps, one of the faster way to do this is like so :

template<typename ForwardIterator>
void makeUnique(ForwardIterator begin, ForwardIterator end){
 std::sort(begin,end);
 std::unique(begin,end);
}

Of course that would be simpler, but this smacks of a homework assignment. If that is the case, the important part is to learn the underlying logic of the algorithm. Thinking along those lines led me to discuss the explicit method.

I am a complete adherent of the STL, however, and, dear OP, if you haven't learned about the c++ standard template library, you should investigate it soon.

dusktreader 137 Posting Whiz in Training

oh and i am using dev-c++ so i cant use strings

You should really consider using something besides dev-c++. Code::Blocks is a common suggestion. You should also know that dev-c++ isn't a language or a standard, so, aside from convenience for the classroom, it has no crucial place in the world of c++ programming.

@Narue std::pair is smart about initializing its members
Hmm...true, but I think you should say std::map. This is a bit confusing for the OP.

Also, I would like to emphasize that it is important to declare amount as an int or other numeric type. If you declare it a string because you split a getline() instead of using the istream >> operator, saying report[account] += amount will give you concatenations of the inputs.

dusktreader 137 Posting Whiz in Training

On this site, a "space" or 2 is sufficient indent. A TAB is too big.

Actually, you shouldn't have actual tabs in your code. That is my opinion, and it is right. Code editors use monospace fonts ( at least they should, for the love of Turing ). Tabs are used by word processors to gurantee alignment of non-monospace fonts. As far as I know, all editors provide an option to replace tabs with some fixed number of spaces. You should use this option. My personal preference is 4 spaces for each indentation level.

dusktreader 137 Posting Whiz in Training

Hrmmmmmmm...

1. Why do you need a screenshot?????
I really have to wonder why you would need a screenshot of a running application. I bet it has something to do with my second question:

2. Is this a homework assignment?
This is the time of year when computer science classes begin. Perhaps your instructor wants to make sure his students can get their system ready to go on assignments... If this is the case, shame on you sir. Find out what libraries you need and install them.

3. Show some effort, for the love of Turing.

That is all.

dusktreader 137 Posting Whiz in Training

I'm trying to find duplicates in an array and removing them by shifting the array index using the same array. I can't figure out where in my code the problem is but I'm still getting a duplicate. Could someone please help pinpoint the problem? I've tried debugging it but I'm not seeing it.

#include <iostream>
using namespace std;

int removeDuplicates(int A[], int n){
	int last = n-1;
	int found = 0;
	//bool flag = false;

	for(int i=0; i < last+1; i++)
	{
		for(int j=i+1; j < last+1; j++)
		{
			if(A[i] == A[j])
			{
				found++;
				for(int k = j;k < last+1;k++)
				{
					A[k]=A[k+1];
					//if(A[k-1] == A[i])
					//	flag = true;
				}
				last--;
				j=j+1;
			}

		}
}
	//found= last-found;
	return last;
}

int main() {

	// Test data
	int n = 24;
	int A[] = {1,1,2,4, 1,1,1,2, 3,5,8,0, 2,-2,-4,1, 9,10,-4,11, 11,8,5,-4};

	// Call
	int last = removeDuplicates(A,n);

	// Print Results
	for(int i = 0; i <= last; i++)
		cout << A[i] << " ";
	cout << endl;

	return 0;
}

I see one fundamental problem here. You are shifting your j index even when a duplicate is found. When you find a duplicate and shift all items, you need to leave the j index in place:

1.  Found duplicate

    i     j
    |     |
    v     v
ABCDEFGHIJEEKLMNO

2.  Shift

    i     j
    |     |
    v     v
ABCDEFGHIJEEKLMNO
           vvvvvv
           ||||||
           //////
          |||||| 
          vvvvvv 
ABCDEFGHIJEKLMNO

3.  Incorrect increment of j

    i      j
    |      |
    v      v
ABCDEFGHIJEKLMNO
          ^
          |_____________There is still a duplicate, but it …
mrnutty commented: Nice Ascii Art and good explanation. +5
dusktreader 137 Posting Whiz in Training

Yes, that is, in fact, what I was trying to say. And, I definitely agree with your second paragraph.

dusktreader 137 Posting Whiz in Training

>If the function may not be implemented in the derived class,
>it really shouldn't be defined as a pure virtual function.

A pure virtual function must be implemented in the derived class, this is absolute. With destructors the implicit implementation suffices, so while you don't see it in the source, it's still there. I don't know if that alters your opinion of broken semantics or not, but there you go.

Hmmm....the generality of the word 'may' may have caused some confusion here. Let me re-word.

If the function might not be fully implemented in the derived class, it really shouldn't be defined as a pure virtual function.

dusktreader 137 Posting Whiz in Training

@Narue
Because of perverse curiosity, I must know. When and why have you used placement new before? Perhaps a hardware interface?

dusktreader 137 Posting Whiz in Training

>So in my view, I'm still right
...

Righteous indignation is as heavy a cross to bear as defending an invalid thesis.

@Mike
She got you. You should at least admit it.

@Narue
You may be right, but I don't completely agree. One of the benefits of using pure virtual functions is forcing derived classes to implement them. Though it may be legal, in my mind it breaks the semantics of abstract inheritance. If the function may not be implemented in the derived class, it really shouldn't be defined as a pure virtual function. I would favor letting the derived class implicitly call the base class non-pure virtual function when the function isn't defined in the derived class. I tend to think that if you are having trouble thinking of a pure virtual function to put in your abstract base class, then perhaps the base class shouldn't actually be abstract.

<brace for the wrath>

dusktreader 137 Posting Whiz in Training

All I was asking for is a little advice in how to setup my algorithm, I can do the code. I am a straight A student (3.871), I made an A in this class in the summer, just with a lot easier teacher. I have never had to learn about prime numbers. I am more interested in learning about functions, parameters, arrays, structs, classes, etc. I could care less about prime numbers, and how to find all even numbers in existence and have two prime numbers that equal them. Is prime number excellence a part of C++.

I understand that you are quite daunted by this homework assignment. Please understand that your professor probably doesn't care whether you love prime numbers or not. Rather, this assignment is a good way for you to

1. Think about how to use logic to solve a problem
2. Implement that logic in a program

Learning about the language mechanics is important. However, understanding how to use logical tools to solve a problem is more important. Logic is universal. Language mechanics are rather limited in scope.

You have all the functions. Now, you just need to think about how to combine them to get a working solution. I assure you, this is a very good exercise for an entry level Computer Science student.

dusktreader 137 Posting Whiz in Training

#include <iostream.h>
#include <conio.h>
void main(void)
{
clrscr();
int i,p;
for(i=1;i<=300;i=i+1)
{
for(p=2;p<i;p=p+1)
{
if(i%p==0)
break;
else
continue;
}
if(i==p)
cout<<" Prime:"<<p;
}
getch();
}

What the #&&$*% is this?

1. void main() is a great way to start fail code
Please, for the love of any deity, use int main.

2. The conio.h is a huge, non-standard fail.
Don't use this. Just don't. It's not standard, it's not cross-platform, and it's
not even very powerful

3. READ THE RULES AND USE CODE TAGS

4. Plain text in a reply is helpful.
Perhaps you should describe what your code is for and why the OP should give a crap about it.

5. Read the original post.
Your solution simply prints all the primes less than 300. This is trivial, and the OP already knows how to determine if a number is prime. His assignment is not so difficult, but this code is anything but helpful to him.

6. Use less pointless code
This is painful:

for(p=2;p<i;p=p+1)  // p=p+1?  really?  really??????
{
    if(i%p==0)
        break;
    else            // There is no point at all to using this
        continue;   // When the if clause fails, of course the loop will continue
}

perhaps:

for( p = 2; p < i &&  i % p != 0; p++ );

7. There are …

dusktreader 137 Posting Whiz in Training

I'm a huge fan of Qt. I build a lot of Qt applications, and I'm really happy with this GUI. Trolltech, the makers of Qt, also provide a full-featured integrated IDE called QtCreator that I actually use for my general purpose c++ coding. Qt is very flexible, has tons of widgets and usefull classes, and it's completely crossplatform. I highly recommend Qt.

dusktreader 137 Posting Whiz in Training
void randnum(double lower, double upper, int n)  // Generate 'n' random numbers uniformly distributed 
{	                                         // between lower and upper limits.
	double a = 0;
	double b = 0;

	srand((unsigned)time(0));

	for (int i = 1; i < n+1; ++i) {
		a = rand();
		b = lower + (a / 32767) * (upper - lower);   // RAND_MAX for MS VC++ Express is 32,767.
		cout << i <<"  " << b <<endl;
	}
}

You need to be very careful with this code. The random number generator should not be seeded more than once in a single program. The time() function returns an unsigned long integer number representing time since the epochs in seconds. If you made two subsequent calls to the randnum() function within the same second, the function would return two identical values.

The problem of producing random numbers with different distributions is solved in two ways. First, you can go and get a library that already has it implemented. Second, you can implement it yourself.

I have created my own RNG class in the past to solve this problem. This can answer the seeding problem in two ways. First, you can make your RNG class a singleton and call srand() in its constructor. I don't prefer this method because singleton classes are not a native concept in c++. I usually lean toward adding a static boolean flag to the RNG class called isSeeded, or some such. Then, in the constructor of the class, you have it …

dusktreader 137 Posting Whiz in Training

However, If you want to maintain const-correctness (and I think that that's usually a good idea), then you don't have to change the function at all, simply use a std::const_cast<int&>() to temporarily suspend the effect of the const keyword on the variable, so your function call would look like this:

The problem I see with this is that it allows the user to pass a constant value to the function, which would then have no effect, depending on the code in Activate.

int Activate( const int& tp, int weaponDamage, int attack );
int result = Activate( [B]5[/B], 6, 7 ); // This is legal, but what is the effect?

I think it is a better idea to make get_tp() return a reference.

dusktreader 137 Posting Whiz in Training

>>Structs are simpler. Structs are old. Structs are not as powerful

May I ask why you think structs are not as powerful as classes in C++?

Polymorphism and Inheritance.

dusktreader 137 Posting Whiz in Training

It does compile fine on my system using gcc. So, again, I think the problem is Dev c++.

I did discover a logic problem in your code however

double TestScores::theAverage(int scores[],int size)
{
     for(int count=0;count < size;count++)
     {
             if(scores[count]<0)//check for element < 0
             {
                throw NegativeNumber(scores[count]);//throw error if < 0
                //this uses the value in the array and returns it to main
             }
             else if (scores[count] > 100)//check for element > 0
             {
                throw LargerThan(scores[count]);//throw error if > 0
                //this uses the value in the array and returns it to main
             }
             else
             {
                 holdelement += scores[count];//no error add it to holdval
                 average = (holdelement / 5.0);//keep a running average of holdval
             }
             // Inside the for loop
             return average; // <------------PROBLEM!!!
     }
     // Outside the for loop
}

You can see here that your function is returning after only the first iteration of the loop. You need to move your return statement outside of the for loop.

I'm not sure that your running average is behaving correctly either. What is the constant of 5.0? Why not just compute the average after all of the elements have been examined and right before the function returns?

dusktreader 137 Posting Whiz in Training

This should work. Your function's definition matches your function's declaration. Your function's call matches both.

Dev C++ causes problems and has compatability issues. Basically, it sucks and doesn't work well with established standards. You should consider getting a new IDE and compiler toolchain. I've heard that Code::Blocks is a nice alternative to Dev C++

dusktreader 137 Posting Whiz in Training

This should work:

int s = b.Activate(war.get_tp(), damage, 50);

//prototype
int Activate ( [B]const[/B] int &tp, int weaponDamage, int attack );
dusktreader 137 Posting Whiz in Training

Thank you very much for your suggestions, Vijayan. I hadn't thought that having different classes for different exceptions was an appropriate formulation.

I respectfully disagree. I believe that different exception types should have different class definitions. This paradigm is used extensively in many C++ libraries. I do agree that you should probably create your own base exception class and then derive from that your different sorts of exceptions specific to your implementation.

This part troubles me:

catch(exception& e) { /*code*/ }
catch(...) { /*code*/ }

It seems to me that the second catch statement is unreachable. If I remember correctly, the exception class is the most fundamental base class for all C++ exceptions. If I am correct, then all exceptions will be caught in the first catch. If you implement your own base exception class, say MathException , then you could have the first catch block look for only MathException instances. I use this sort of thing often. It allows you to catch exceptions that are caused in your code, and the generic exception catch will report if something unanticipated happens.

By the way, your code looks very good. Very nice work in self-education.

dusktreader 137 Posting Whiz in Training

You really need to post code demonstrating your problem. We have good imaginations, but this is a little sparse....

dusktreader 137 Posting Whiz in Training

Structs are simpler. Structs are old. Structs are not as powerful.

If this isn't for homework, you should definetly use a class here. Take the extra time to figure it out, because this sort of functionality is exactly what classes ( well, all OOP really ) was designed to provide. You will need two functions that explicitly manage the data in your struct. It would be much better to design a simple class to provide this functionality. Writing a basic class for this will not be that hard, I assure you, and it will be a great exercise for expanding your programming abilities.

The STL (sets, vetctors, etc.) is a native C++ paradigm. I encourage you to embrace C++ classes as well. There is little reason to mix C style structs with C++ containers in this case.

dusktreader 137 Posting Whiz in Training

You could use the strcpy() function to acquire this functionality:

int i;

            for(i = 0; i < length; i++)
            {
                strng[i] = str[i];
            }
dusktreader 137 Posting Whiz in Training

Understanding pointers is CRITICAL to mastering C and C++. You should really go out onto the internet and read about pointers. You should work through some tutorials and examples. There is a lot of core concepts in pointer management. I don't think it would be appropriate to discuss it all here.

That being said, here is a concept that will help you. When you declare an array:

int myArray[10];

the variable myArray is actually a pointer. It is a pointer to the fist int in the array.

Please read up on pointers. It will be well worth your time. These will get you started:
http://www.cplusplus.com/doc/tutorial/pointers/
http://www.augustcouncil.com/~tgibson/tutorial/ptr.html
http://home.netcom.com/~tjensen/ptr/pointers.htm

dusktreader 137 Posting Whiz in Training

This definitely sounds like a job for a class not a struct. I'm surprised at the mixture of the STL with a struct that requires specific functionality. Is this an assignment for a class? If so, I wonder why your teacher isn't asking for a class with overloaded operators.

dusktreader 137 Posting Whiz in Training

I would in hindsight agree with dusktreader, however make one final suggestion.

Instead of a constant sized array of data consider using stl vectors or llists which let you read any amount of input without knowing its size first. If you know the size of input will never change i guess the above way is fine but its just a thought.

I completely agree. This code could be improved greatly by using the Standard Template Library.

However, it is obvious that this person is studying computer science. Often teachers/professors insist on students using old programming paradigms that are carry-overs from C. To me, this practice is asinine, because many programmers continue to use these methods beyond the classroom when there are simpler, cleaner, and more robust ways to implement the same functionality. It is especially annoying when the preferred method is native to the C++ language!

So, I didn't want to confuse the OP. However, if you are listening, dear OP, please read up on the use of std::vector and the other joys of the c++ standard template library. I promise you that once you embrace the STL, your code will improve and you'll be spending less time bounds checking and searching for seg faults and more time producing good code.

dusktreader 137 Posting Whiz in Training
char sentance[40];

int i = 0;

srand((unsigned)time(NULL));
for( i = 0; i <= 20; i++)
{
    strcat_s(sentance, article[rand()%5]);
    strcat_s(sentance,noun[rand()%5]);
    strcat_s(sentance,verb[rand()%5]);
    strcat_s(sentance,preposition[rand()%5]);
    strcat_s(sentance,article[rand()%5]);
    printf("\n\n%s\n\n'", sentance);
}
}

My guess is that you are overrunning your sentence array. First, you should make it larger. 40 characters probably won't consistently be enough. Secondly, you need to clear your sentence variable right after you pring it each time. Using the strcat() function, you are just adding more and more words to the same sentence. You'll run out of your 40 characters rather quickly this way!

dusktreader 137 Posting Whiz in Training

Does it look clean?

The code is actually pretty clean for a beginner! +1 for you. There are a few things you could do to improve it further.

1. Put the score input and score display sections in their own functions. It is always preferable to keep the main function very sparse and easy to read. This way, you can quickly look at main(), and (assuming your functions are named well) quickly understand the logic and data flow.

2. Align your comments.

int dummy1;                       // A dummy integer
double aRealNumberButStillDummy;  // A dummy real number

It's much easier to read code if all of the comments are aligned. This also helps the reader quickly seperate each line of code from its explanation. The exception here would be your block (//begin/end) comments. By the way, I'm impressed that you use this idea. It can help when your nested logic gets deep. Of course, it is best to avoid deep nesting, but....

3. Split long lines into two. If you have a long line of code, try to find a logical break point, and seperate it into two lines. This will make your code easier to read. Don't split lines for comments, however. If you need to read a comment, it's ok to have to scroll right.

Pretty good altogether. Keep up the good work. You will probably be a successful programmer!

Oh, and use a better sort method. Just kidding. But seriously, bubble sort makes …

dusktreader 137 Posting Whiz in Training

I wouldn't use getline for this. If you do so, you must take responsibility for tokenizing the lines and converting string data. The iostream library can do this automatically for you, so using ifstream and the >> operator is correct.

My guess is that you are reading all of the data into the same variables over and over.

this code:

while( fin && !fin.eof() )
{
    Node * temp = new Node;
    char first [100];
    char last [100];
    int acctnumber;
    double balance;
    //char notes [100];
    char created [80];
    char modified [80];
    fin >> first >> last >> acctnumber >> balance >> created >> modified;
}

Doesn't do anything with the data it has read. It simply goes to the next iteration of the loop and reads that data into the same variables as the previous loop.

My guess is that your output is the last record in the file repeated so many times.

My suggestion for you would be to create an array of structs containing the data read from file. That way, you can store all the data you have read without overwriting anything.

Something similar to this should work for you:

#include <iostream>
#include <fstream>

using namespace std;

struct MyData
{
    char   someString[100];
    int    someInteger;
    double someReal;
};

void myReadingFunction( ifstream& fin, MyData data[], int& count )
{
    count = 0;
    while( !fin.eof() )
    {
        fin >> data[count].someString
            >> data[count].someInteger
            >> data[count].someReal;
        count++;
    }
}

void myPrintingFunction( MyData data[], int count …
dusktreader 137 Posting Whiz in Training

The purpose of homework is to learn how to solve problems similar to the ones you will face in your career. You must try to do your own homework. When you have struggled through some code and feel hopelessly stuck, post specifically what you are trying to do with your code and the code you have tried. People on this forum will then try to explain the underlying concepts and provide abstract examples. No one on this forum should supply solution code to you.

Please, please get the text book. If you can't get it, scour the internet for information. There is so much information about programming online. You could go from caveman to Linus Torvalds by simply using the internet IF YOU ARE WILLING TO INVEST THE EFFORT.

Now, go forth and code.

Come back when you have been defeated. We will pick you up, dust you off, and give you strategies to continue the fight.

dusktreader 137 Posting Whiz in Training

Hi guys....

if((number[i][j])%2==0){

This is where your program goes wrong. You are testing whether the value of the "matrix" at i,j is even or odd. Since you haven't initialized any of your values in the array, this will produce undefined behavior. When you allocate memory for an array (dynamically or statically), the program simply reserves the space. It does not set any of the values in the memory. So, there will be random bytes in the allocated space that may have been meaningful to whatever objects were stored there before. As Fbody said, you need to test your indices for evenness (in particular the j index).

dusktreader 137 Posting Whiz in Training

This is a incomplete code
Complete this code by using Dev C++ for practice

Don't post complete code for this. I'm almost certain this person wants you to do his homework for him. Asking for the code to be completed "by using Dev C++" is almost a certain give-away. No one encouraging practice would suggest a specific IDE, unless they are trying to teach Eclipse or Visual Studio.

dusktreader 137 Posting Whiz in Training

You could do this in an even cleaner fashion by using references. If you use const references, you can pass in values that have not been saved in a variable:

#include <iostream>
#include <vector>

using namespace std;

const double& max( const double& a, const double& b )
{
    return a > b ? a : b;
}

int main()
{
    cout << max( 5.0, 7.0 ) << endl;
    double a = 13.0;
    double b = 11.0;
    double c = max( a, b );
    cout << c << endl;
    return 0;
}