Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Aditya_13: While your willingness to help is commendable, it is ill-advised in this instance. Why? Because the OP didn't show any evidence that they had put any effort into the project themselves. There is a rule here a Daniweb that querents have to give some indication that they have tried to solve a problem themselves before they asked for help, whether through posting their code, or asking a meaningful question about the problem set that shows that they had at least thought through the problem.

SUBHENDU_1 did none of that. Instead, the OP simply did a datadump of the assignment and demanded that we provide a solution. This is called cheating in any school worth its salt, and we won't give support to such laziness. The OP will learn nothing from having the solution provided to them, other than an inflated sense of entitlement. If for no better reason than the fact that one of us may have to work with this person someday, the last thing we want is to help someone get a degree they didn't earn.

While it is sometimes a tricky line to avoid crossing - most of us here have done either too much or too little to help someone in the past - this case is clear-cut. The OP hasn't given any sign of trying to solve the problem, and probably spent more time finding this forum to beg for a handout than it would have taken to write the damn program themselves. None …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The first step is to import the GUI library you mean to use. Since a set of bindings for Tk is included with the Python standard library, that's probably the one you'll want to use; let us know if you want a different toolkit such as wxWindows or Qt.

Assuming for the moment that you're using tkinter, You probably want to start with one of the tutorials on the Python website. To give a thumbnail sketch of what you'd need to do, you need to import tkinter,

import tkinter as tk

(I chose to shorten the tkinter package name rather than import it en masse, because even in a simple program like this it is better to limit namespace pollution as much as possible.)

Geberally, you will want to define a subclass of the Frame widget next, as a way of organizing the widgets that will go in said frame. In this case, you will want to make the number to be guessed at and the number of guesses member variables of the frame as well:

class GuessingGame(tk.Frame):
    def __init__(self, master=none)
        tk.Frame.__init__(self, master)
        self.target = random.randint(1, 50)
        self.tries = 0
        self.correct = False
        self.pack()
        self.createWidgets()

You would then define the methods for setting up the widgets, event handlers and so forth.

Once you've defined the GuessingGame class, you would then create a Tk root widget in the main program:

if __name__ == "__main__":
    root = tk.Tk()
    game = GuessingGame(master=root)
    game.mainloop()
    root.destroy() …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Can you clarify what you mean, please? Is it that changing the source code leads to it failing to have any output at all, or is it that the output window is closing as soon as you finish the input?

I ask this because the latter problem is a known bug in the older Bloodshed Dev-C++, one which was never patched in the original. Unfortunately, that version of Dev-C++ hasn't been maintained in a decade, so not only was the bug never fixed, the IDE and the compiler bundled with it are long out of date. The solution is to instead get a newer IDE such as the Orwell Dev-C++ fork, Code::Blocks or Eclipse Luna, each of which avoids this particular bug.

If it is a problem with your code, however, then we would need to see at least the part of the program that has been changed, and a more detailed description of the change and how the program is misbehaving.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I know I've been using this a lot, but the OP in this case really needs this particular anvil dropped on his head.

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

We take this issue seriously here. Very seriously. Asking us to …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

respectfully you don't have any right to notify of which country I belong to and what are our professors teaching us?

I apologize for overstepping on this matter, then. Your location is posted in your member profile, but you are correct, it was inappropriate for me to point it out.

As for what your professors are teaching, that was meant as a warning to you that what you are being taught is at least partially invalid, and to be aware that your coursework is likely to give you little traction in modern programming.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Let's see, old style headers with extensions, <conio.h>, void main() - let me guess, your professor is using Turbo C++ as your compiler?

/me checks OP's locations Ah, Pakistan, that explains that. This comes up a lot, and the answer is that there's nothing to be done about it. Pity, there's really no chance of you being allowed to use something more modern there, as the university system in Pakistan (like that in India) standardized on Turbo C++ decades ago and won't budge an inch on the subject. It's unfortunate, as it means you are being taught a version of C++ that is nearly twenty years out of date, and using a compiler so old that you can't even install it on newer PCs without using a DOS emulator, but as long as you are going to class at a university in your country, there simply isn't any alternative.

The first piece of advice is to be more careful with indenting your code. Proper indentation makes a world of difference in how readable the code is. The specific indent style is less important than being consistent about it; the whole point is to make the different parts of it stand out.

The other thing is that, no matter what the compiler accepts, and no matter what your professor may have told you, void main() is not valid C++. In C++, the main() function must always return an int, either zero when the program succeeds or an error code …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As Moschops said, the NULL pointer is essentially a marker. Setting a pointer to NULL is a way of indicating the pointer is in an unusable state.

Now, as for it's uses, they mostly relate to handling dynamic memory. You generally want to initialize any pointer that you don't have an immediate value for to NULL, as an uninitialized pointer may or may not point to usable memory. If it is pointing to unusable memory, accessing it is almost certain to cause a memory violation exception such as a segmentation fault. and if it does point to usable memory, you won't know where it is pointing to, which mans that accessing that memory through it, or (even worse) changing the value of that memory could have unpredicatable results. To prevent this, you generally want to set a pointer to NULL, which is guaranteed to segfault if you access it; it is better for the program to fail outright in most cases than to continue in an unknown state. More importantly, because NULL is a known value, one which is always invalid, consistently setting unused pointers to NULL lets you check the state of the pointer. If you test the pointer's value against NULL before attempting to dereference it, you will know if the pointer is usable or not.

It is also important when working with dynamically allocated compound data structures, such as linked lists or trees. The usual practice is to use the NULL pointer to indicate the end of …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There's a lot of (well deserved) hate for goto, but it's not inherently broken or bad.

True; there are places where it is justified, and where it makes sense to use it. However, such cases are few and far between. More importantly, it takes some experience to know when it is reasonable to use it, which is why novice coders are generally steered away from it. The goto statement is very powerful, more powerful than is usually necessary, and that power takes discipline to use effectively.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You're correct that gotoxy() is specific to the Borland compilers; there's no standard equivalent for it, exactly, but for this purpose, the code you have is good beginning. I would recommend making a few changes to get it working:

void draw_box(int width, char top, char sides, char bottom)
{
    cout << top 
         << setw(width - 2) << setfill(top)
         << top << endl;

    cout.fill(' ');
    for(int i = 0; i < width; i++)
    {
        cout << side
             << setw(width - 1) << right << side
             << endl;
    }

    cout << bottom
         << setw(width - 2) << setfill(bottom)
         << bottom << endl;
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you don't mind me asking, did your instructor actually teach you to use goto, and more importantly, were you actually directed to use it? I would find it deeply concerning if a professor were to even mention goto in an introductory course. Actually teaching its use is simply unacceptable.

The main problem with goto is that it is unstructured; it can be used (and abused) to create an incomprehensible flow of control if it isn't used with great care. The goto statement is more powerful than is generally needed for flow control, capable of creating labyrinthine programs often called spaghetti code because of the twists and turns it takes.

It also interferes with the ability of the compiler to produce optimized code; because it is harder for the compiler to analyze, it means that many optimization techniques cannot be applied.

More importantly, it is simply unnecessary for ordinary flow control - more structured alternatives such as while() and for() combined with restricted forms of goto such as continue or break can express almost all flow processes needed even more effectively. Most newer languages don't even provide goto statements because of the potential for misuse, and it is a once-in-a-career event for a C/C++ programmer to find themselves in a position where they would want to use it, something you would do only if all of the alternatives were worse. There are some exceptions, where goto makes the code easier to read - certain kinds of state machines, for example …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ah, there seems to be an issue with terminology that is confusing both you and us. To clarify, a struct is not a function; it is a data structure declaration. By referring to multiple functions, you got us wondering if there were part of the code that was missing.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I should also add that, strictly speaking, in C prior to the C99 standard, all declarations within a function needed to be made before any other statements. I only bring this up because you #include <conio.h>; the console I/O library is not a standard part of C, and is associated with older (that is, pre-C99) Borland compilers. Those compilers shouldn't let you do both.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As rubberman said, your statement doesn't make much sense. Could you please explain a little clearer just what it is you need help with?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Would mind explaining why you want to separate them in this manner? It would go far in giving us a better idea of how to help you.

However, as I've already explained, you can't write the TestAndSet() function in C, or in any high-level language for that matter, because it won't compile to an atomic action (that is, one which cannot be interrupted partway through - usually, a single CPU instruction, and specifically one which locks out interrupts as it executes; in modern processors, it must lock any other cores out from accessing the memory bus, as well). You must have an assembly language procedure for that, or at the very least a pair of assembly procedures that will block and unblock the process scheduler and interrupt handlers while the mutex code is in the critical section.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you don't mind me asking, why would you need to, given that Excel can sort a row or column of data with a single push of a button? I don't doubt you need it, I'm just looking for some background on the matter.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, first off, this code as posted isn't valid; you have the TestAndTest() function (which I assume is actually supposed to be TestAndSet(), but that's an aside) inside the main() function, which is an error (C does not allow for nested functions). I assume it is a quirk of cutting and pasting the code her, however.

I would recomend a more consistent indent style as well; here is your code re-indented (using Astyle set to Allman style) for readability:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/time.h>

#define DATASIZE (10<<20)
bool lock = false;


bool TestAndSet(bool *target)
{
    bool rv = *target;
    *target = true;
    return rv;
}


int main()
{
    double A[200][200];
    double B[200][200];
    double C[200][200];
    int i, j, k, m; 
    int outfile, result, count; 
    int counter = 0;
    unsigned seed;

    struct timeval before, after;

    char *buff;

    buff = (char *)malloc(sizeof(char)*(10<<20));

    srandom(seed);


    for (i=0; i<200; i++)
        for (j=0; j<200; j++)
        {
            A[i][j] = random()/100.0;
            B[i][j] = random()/100.0;
        }

    gettimeofday(&before, NULL);

    pid_t pid ;
    pid = fork () ;

    if (pid == -1)
    {
        perror ("fork faild") ;
        exit(EXIT_FAILURE);
    }

    else

        if (pid >=0)
        {
            if (pid == 0)
            {
                for (m=0 ; m<10 ; m++)
                {
/* I/O */ /* STARTING I/O CRITICAL SECTION */
                    do 
                    {
                        while(TestAndSet(&lock))
                            ;

                        printf("I/O process iteration was allowed to start \n");
                        outfile = open("testfile", O_RDWR|O_CREAT|O_APPEND, 0777);
                        if (outfile <= 0)
                            perror("Error opening file\n");
                        else 
                        {
                            result = write(outfile, buff, DATASIZE);
                            if (result <= 0) …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As for compound data structures, I can see that you haven't covered them, which means that it probably means that you aren't free to use them for this project; however, I can explain them ahead of time for you so you will have a bit of a leg up when you do cover them.

In C++, struct and class are basically the same, except for the visibility of the members; however, structs are usually used for POD (Plain Old Data, that is, member variables but not member functions). For this reason, I'll cover structs first, then shift to classes afterwards.

A struct basically is a name for a group of related variables. Unlike an array, which is homogeneous (that is, every element is the same type) and indexed (i.e., the elements are referred to by number rather than name), a struct's member variables are named, and can be of different types. For your particular case, you would probably want to define a Point2D type, and then use that to define a Line2D type.

struct Point2D
{
   double x, y;
};

struct LineSegment2D
{
    Point2D start, end;
};

The member variables can be accessed using the member reference operator (or dot operator, .), like so:

LineSegment2D line_1;
line_1.start.x = 2.0;
line_1.start.y = 1.1;
line_1.end.x = 4.5;
line_1.end.y = 3.8;

How you could apply this to re-writing your functions might go like so:

LineSegment2D* getLineSegment() //Reference function
{
    LineSegment2D* line = new LineSegment2D();

    cout << "Enter x-y …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

By explict function, all I mean is a function which explicitly returns a value. For example:

int foo(int bar)
{
    return 23 * bar;
}

which would be used like so:

int quux;

quux = foo(17);    // quux now assigned the value 23 * 17 == 391

It is related to why most procedural sub-routines are referred to as 'functions' in the first place: a function with a return value is conceptually and semantically similar to a mathematical function (though they aren't strictly the same thing; a mathematical function defines a relationship between its domain and its co-domain, while a C++ function defines a computation that returns a value).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In C, you cannot directly compare compound structures such as strings the way you can simple values such as ints or doubles; or rather, you can in the case of strings, but you would end up comparing the memory addresses where the strings begin rather than the strings themselves.

What you need to use a function that iterates through the strings and compares them element by element. Not surprisingly, the standard string library includes a function for just this purpose, namely strcmp(). However, there's a catch: strcmp() does not return a boolean result, but instead compares the strings lexicographically. If the strings are equal (i.e., they hold the same characters), then strcmp() returns 0; otherwise, it returns -1 if the first string comes earlier lexicographically than the second, otherwise it returns 1. For example,

strcmp("abc", "abd")

would return -1, while

strcmp("xyz", "mno")

would return 1.

The practical upshot of this is that you need to change the if() statement to read something like this:

if((strcmp(Worker_name, worker1.Worker_name) == 0)
  || (strcmp(Worker_name, worker2.Worker_name) == 0))

As an aside, I would recommend against passing any string directly to printf(), as it can be a security risk in some cases. Instead, use

 printf("%s", Worker_name);

Finally, I would strongly suggest that you remove the reference to <conio.h>; not only aren't you actually using any console functions, the header itself is non-standard, and only a handful of now long outdated compilers ever supported it in the first …

Seandean_1 commented: it is printing worker name doesn't exist +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While the program looks good functionally, I would like to make some stylistic suggestions.

  1. You generally want to separate the functions which operform computation from those which do input and output. This principle of decoupling serves to make the program more modular and easier to fix and modify. Separating model from presentation is an important factor in making code reusable, as well, and thus it is a good habit to get into.

  2. The opposite principle, encapsulation, says that whenever possible, related data should be bundled together into a composite structure, and that the operations on the data structure should be bundled with it as well. Again, this makes the code more modular, by separating concerns. If you have covered structs or classes in your coursework, it would make sense to define a Coordinate structure (either a struct or a class) which can be passed around and operated on as a unit.

  3. It is much, much better to use explicit function returns rather than passing values back via reference parameters; it makes it clearer what the purpose and value of the function is if the function is returning a value explicitly. Reference passing of return values is based on side effects, and often opaque ones at that; unless you thoroughly document the reference side effect, future maintainers may not even notice it, and even then misunderstandings tend to creep in. This makes for another reason to bundle the data into structures - you can pass a compound structure via function return, …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

For what it is worth, here is my full solution, which may or may not make enough sense to you to give you a leg up:

#!/usr/bin/python3
# Rock Paper Scissors, Project 2, Tadd O'Bannion

import sys
import random

ROCK = 0
PAPER = 1
SCISSORS = 2

choices = ['Rock', 'Paper', 'Scissors']

def main():
    print("-" * 50)
    print("Welcome to the wonderful world of Paper Rock Scissors! ")
    print("-" * 50)
    print(" 1) One Player Game ( One human playing against the computer.) \n")
    print(" 2) Two Player Game ( Two humans playing against each other.) \n")
    print("    Choose game type or press ENTER to quit game. \n")
    print("-" * 50)

    menuChoice = input("Please enter a choice from the above menu: ")

    print("*" * 40)
    print('You have decided to ', end='')

    if menuChoice == '':
        print('exit the game. Goodbye.')
        sys.exit()

    elif menuChoice == "1":
        print("play a one player game against the computer.")
        print("*" * 50)

        player1_name = 'Human Player'
        player2_name =  'Computer'
        player2_choice = random.choice([0, 1, 2])

        print_menu()
        player1_choice = read_menu_choice(0, 2)

    else:
        print ("play a two player game against another human.")
        print("*" * 50)
        player1_name = 'Player 1'
        player2_name = 'Player 2'

        print(player1_name)
        print_menu()
        player1_choice = read_menu_choice(0, 2)
        print()
        print(player2_name)
        print_menu()
        player2_choice = read_menu_choice(0, 2)


    print_player_choice(player1_name, player1_choice)
    print_player_choice(player2_name, player2_choice)
    winner = print_match_results(player1_name, player1_choice, player2_name, player2_choice)



def print_menu():
    for n in range(3):
        print(" {0}) {1}".format(n, choices[n]))
    print()


def print_match_results(player1_name, player1_hand, player2_name, player2_hand):
    outcome = ['Tie',
               'Paper covers Rock',
               'Rock smashes Scissors',
               'Scissors cuts Paper']

    combinations = {ROCK:     {ROCK: [0, …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oops, I just noticed that I dropped the player2_hand == part of the each of the inner elifs in that second function. My bad.

def print_match_results(player1_name, player1_hand, player2_name, player2_hand):
    ROCK = 1
    PAPER = 2
    SCISSORS = 3

    outcomes = ['Tie',
                'Paper covers Rock',
                'Rock smashes Scissors',
                'Scissors cuts Paper']

    outcome_str = '{0}, {1} wins!'

    if player1_hand == ROCK:
        if player2_hand == ROCK:
            print(outcome[0])
        elif player2_hand == SCISSORS:
            print(outcome_str.format(outcome[3], player1_name))
        else:
            print(outcome_str.format(outcome[1], player2_name))

    elif player1_hand == PAPER:
        if player2_hand == PAPER:
            print(outcome[0])
        elif player2_hand == ROCK:
            print(outcome_str.format(outcome[1], player1_name))
        else:
            print(outcome_str.format(outcome[3], player2_name))

    elif player1_hand == SCISSORS:
        if player2_hand == SCISSORS:
            print(outcome[0])
        elif player2_hand == PAPER:
            print(outcome_str.format(outcome[3], player1_name))
        else:
            print(outcome_str.format(outcome[2], player2_name))            
    print()
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The problem is quite simple: your indentation is off. Lines 25-65 need to be one level of indent to the right.

Please don't tell me how to shorten it, I want this to be a very understandable (from a very new beginner perspective) program so I want to keep it simple.

Actually, shortening it in certain places would actually make it easier to understand, beginner or no, just by reducing repetition. For example, just this one function would make the program easier to read while removing several repeated sections of code:

def print_menu():
    print(" 1) Paper")
    print(" 2) Rock")
    print(" 3) Scissors")
    print(" 4) Quit")
    print()

A slightly more elaborate, but even more useful, example would be:

def print_match_results(player1_name, player1_hand, player2_name, player2_hand):
    ROCK = 1
    PAPER = 2
    SCISSORS = 3

    outcomes = ['Tie',
                'Paper covers Rock',
                'Rock smashes Scissors',
                'Scissors cuts Paper']

    if player1_hand == ROCK:
        if player2_hand == ROCK:
            print(outcome[0])
        elif SCISSORS:
            print("{0}. {1} wins!".format(outcome[3], player1_name))
        else:
            print("{0}. {1} wins!".format(outcome[1], player2_name))

    if player1_hand == PAPER:
        if player2_hand == PAPER:
            print(outcome[0])
        elif ROCK:
            print("{0}, {1} wins!".format(outcome[1], player1_name))
        else:
            print("{0}, {1} wins!".format(outcome[3], player2_name))

    if player1_hand == SCISSORS:
        if player2_hand == SCISSORS:
            print(outcome[0])
        elif PAPER:
            print("{0}, {1} wins!".format(outcome[3], player1_name))
        else:
            print("{0}, {1} wins!".format(outcome[2], player2_name))            
    print()

At this point, though, we might be pushing things a bit for you, so if you don't quite get it feel free to ignore this.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Part of the problem lies in trying to write out the structs directly, rather than writing the individual fields out in an system-independent form (a process called serialization). A struct is not necessarily straight data; there may be padding for architecture-specific memory alignment, for example, and if the struct contains a pointer, it may hold a direct reference to an object in memory which won't necessarily be in the same location when the struct is reconstituted, or even exist at all anymore.

While this particular struct should be writeable, it is better to serialize the data rather than just assume that you can write out and read back the data structure as a whole. So, instead of

count = fwrite(&single_match,sizeof(single_match),1,binary);

you would be better off writing

char team_a[20], team_b[20];
int goals_a, goals_b;   /* at the start of the function */
/* ...  */

memcpy(team_a, single_match.team_a);
count = fwrite(team_a, sizeof(char), 20, binary);
check = check_write(count);   /* a utility function that does the write checking */
memcpy(team_b, single_match.team_b);
count = fwrite(team_b, sizeof(char), 20, binary);
check = check_write(count);
goals_a = single_match.goals_a;
count = fwrite(&goals_a, sizeof(int), 1, binary);
check = check_write(count);
goals_b = single_match.goals_b;
count = fwrite(&goals_b, sizeof(int), 1, binary);
check = check_write(count);    
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Darwin_1: You might want to check the timestamp on the thread; Baudday hasn't been active on Daniweb in three years.

Also, it is generally considered bad form to ask for code without showing your own work first. To quote the Daniweb forum rules in this regard:

Do provide evidence of having done some work yourself if posting questions from school or work assignments

(You might also consider the rules Do not hijack old forum threads by posting a new question as a reply to an old one and Do post in full-sentence English as well, in this case.)

While this is aimed primarily at preventing cheating by students, it applies to anyone who fails to demonstrate that they have made a good-faith effort to work out their problems before coming here. While you may in fact have done so, we have no way of knowing this without some token of your previous work being offered. It doesn't have to be code - an explanation of what you have already done will suffice - but that is the surest way to convince us you are serious about solving the problem and not just lookiong for someone to do your work for you.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There are two really simple approaches you could take:

  1. Use two loops, inner and outer, which step through the array. Have a second array hold any duplicate values you find.

  2. Sort the array (or a copy of it if you need to preserve the original order), then walk through it and see if there are any runs of duplicates. Again, you may want to have a second array to hold the found values so you don't get redundant answers.

Neither of these approaches is very efficient, but for such a small data set, that's of minimal concern.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Not exactly; as was explained above, in the old Borland C++ compilers, there was a macro actually called randomize() that was basically a shortcut for both initializing the randomizer and returning a random value. While I don't know the actual implementation, I'm guessing it was something along the lines of

#define randomize(n) srand(time(NULL)); n = rand();

If anyone could give more details, it would be... oh, who am I kidding? It wouldn't be worth much of anything to know exactly, since it is basically a dead issue for anyone using a standards-compliant compiler and library.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

deleted for duplicate post

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

rose_2: While your enthusiasm for answering the question is commendable, it is generally considered a poor practice to provide outright answers to problems when the OP hasn't demonstrated that they had already made a good-faith effort to solve the problem before posting here - it encourages cheating, or at least a lack of effort, and does little to actually help the students learn to program.

This can be a fine line at times - one I and most of the other regulars have inadvertently crossed at one time or another - but this particular instance is clear-cut: the OP basically posted their problem set without any indication that they had done any work on it themselves, for an assignment that shouldn't have required more than a token effort to solve.

gencc: Seriously, you needed to even consider this? You probably could have done it yourself in less time than it took to post the question, and yet you felt you needed to beg for a hand-out? This is a sign of a student who belongs in a different major, or maybe out of college entirely. If I knew who your professor was, I would e-mail them a link to this thread straight away and let the consequences fall on you for your lack of academic honesty.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would add that the Travelling Salesman Problem (which this could be, depending on you interpret the traversal requirement) is known to be an NP-Hard problem, so even if you succeed in getting it to work, it may have quite a long run time depending on how many nodes the graph has to cover. Of course, you could just try proving P=NP and thus showing that a shorter run time may be possible, but that's rather a tall order to fill...

rubberman commented: As in a PhD thesis problem? :-) +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, the list of suggestions linked to above is still valid, and while some are a bit small for what you want, plenty of those examples would make a suitable semester project.

Are there any requirements or limitations on the projects or types of development tools that you need to comply with? That alone could shape the decision, and we'd need to know what those were before we could give you helpful advice. Suggesting a web service project isn't going to do you any good if you need to write the project in Turbo C++, for example.

What courses have you covered and understood well enough that you feel you could dig into the subject matter a bit deeper? If you have, for example, covered a course on compiler design, you could design a simple language that is subset of, say, C, but adds some feature that you have always felt was missing. Write that feature into a your toy compiler, explain how the implementation works, and provide an argument for why that feature adds something to the language, and you've easily got enough work for a semester (actually, that's more of a thesis-level project - indeed, it is sort of the classic thesis project in some universities - but you get the idea).

Or perhaps we should approach this from another direction: what interests you? Is there any significant project or new idea that lights a fire under your a-- and makes you want to rush out to work …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While this is true, the fact is, you didn't ask for help with a specific issue; you simply gave us the problem statement and a plea for assistance, without any indication of what kind of difficulty you were having with it. You also showed no evidence of your prior effort, which is directly contrary to both the letter and the spirit of the forum rules, which state:

Do provide evidence of having done some work yourself if posting questions from school or work assignments

While my reply was perhaps unnecessarily snide, the point remains: we need you to show us what you have tried to do so far, and tell us what you are stuck on, so we at least know how to try and help you.

In order to give any help at all, we would at the very least have to know how you are representing the vectors (as a three-element array, for example, or as a class or struct, or even as disconnected floating-point variables - hopefully not the latter, but it is a possible representation), and whether you had any functions or methods to operate on that representation already written.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Generally speaking, you want to avoid sharing the variable directly at all; global variables are generally considered an anti-pattern, something to avoid unless there is no alternative.

When you need to access a variable in more than one function, you usually want to pass the variable (or a reference or pointer to it) as an argument to the called function instead. This makes the function more modular and easier to reuse, and helps avoid difficult-to-detect side effects. By parameterizing function rather than relying on implicit global state, it makes for a cleaner interface between the functions.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

<RANT>
Something has been nagging me about this problem set since it was first brought up, and I think I've figured out what it is: the assignment itself.

It's just a stupid way of doing this. Period.

Seriously, no experienced programmer would solve this problem like that. Ever. This is the sort of thing report generators are for, and report generation has been a solved problem since the 1960s. You would have to be out of your mind to hand-code something like this, because doing so is a terrible waste of time and effort when you could have it done in a fraction of the time with better results using off-the-shelf tools.

I know it is for a class assignment, but that just makes it worse. It is a poorly constructed problem set that teaches all the wrong lessons, and should never have come across any student's desk anywhere. It would make more sense to teach how to design the blasted report generator itself than to teach students to manually write reports, and honestly, just as fast and probably easier on the students.

The professors - and there are many of them - who teach this way are both lazy and incompetent, and should have never have been allowed to set foot in a classroom in an instructor's role. I don't care how good a researcher they are, if they cannot teach in a classroom setting, they shouldn't be required to.

This whole project is symbolic of the horrid …

NathanOliver commented: So true. This should be a DB and report software +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

write a program for left recursion?

Setting aside the fact that you are asking us to do your work for you, which is against the general policy of Daniweb, this sentence (fragment) doesn't make much sense.

I assume what you meant was that you need to write a parser that handles left recursion in the target grammar. There are two basic approaches to doing this, but neither of them a simple, and they certainly aren't something even the wizards of Daniweb could just whip up, at least not without knowing the grammar in question.

The first approach is to write a bottom-up parser, assuming an LR(k) grammar. However, writing a such a parser by hand simply isn't feasible; they are usually generated, which means you would need to write a parser generator rather than a parser per se. That, needless to say, is a lot of work, and we'd need to see the grammar first to know just what type of parser would be suitable.

The other alternative is to convert the left recursions to right recursions, making it feasible to write a top-down recursive-descent LL(k) parser, which is pretty much the only type suitable for writing by hand. That isn't an easy thing to get right, and no matter what the working grammar will still differ subtly for the language's reference grammar. This is probably what you wanted, but if so, where's the grammar to transform?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The reason is simple: the variable sample is not external to the main.c file, and in fact is a local variable of the main() function itself. When you declared the variable as extern, you were telling the linker, "I want to access a variable defined in another object", which isn't what you were doing at all.

It should make sense once you understand what extern is meant for. My guess - because it is a common misunderstanding, and one I had made myself at one time - is that you expected the extern specifier to make the local variable visible to the other file, but this in in fact the opposite case.

The primary purpose of the extern specifier is to assert that a variable of that name can be found somewhere other than the file the extern declaration appears in - it is most often used in header files to allow a shared variable used by a linked library to be accessible by programs linking in said library. This allows the variable to be made visible via the header, but avoids the problem of redeclaration, because the actual declaration is in the library. So, if you have a shared variable foo in foo.c:

int foo = 42;

you would have it declared in the header, foo.h:

extern int foo;

which could be then #included by a program file, say main.c:

#include "foo.h"

int main()
{
    printf("Foo == %d", foo);
    return 0;
}

In …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Interestingly, either you or a classmate of yours posted essentially the same issue some four days ago, under a different username. You might want to view the answers given at that time.

Given what you are saying, I gather that most of the code was given to you by the professor as a 'fill in the blanks' problem (see, mike_2000_17? I told you those sorts of problems are common). What parts in particular did you need to change, and how are the results differing from the output the professor gave? I assume that the main question is the formatting of the output, given the differences in the two screenshots, but is there more to it than that?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

kalsu: Not only are you doing exactly what we told the OP not to do, you are hijacking another poster's thread to do it. If you persist in this sort of behavior, you are likely to get banned from the site.

Please start a new thread, and explain a) what you have already tried to do to solve your homework problem, and b) what problems you are experiencing in solving it.

If you want a free homework solution given to you, you have come to the wrong place; we recommend you quit the course and find something you are more suited to than programming. Otherwise, show us that you have made a good-faith effort to do the work yourself before coming here looking for help.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Once more with my standard reply for this sort of thing:

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic ethics on your part, …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There should not be a '.cpp' extension on the header file, just '.h'.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The error is a very simple one: you misspelled the header name in your program source file. Just change the 'g' to an 'e' and it should go through correctly.

BTW, I would do four other things. First, I would remove the using namespace std; from the header file, and explicitly scope the standard library functions and objects using std::, like so:

std::cout << "The area of the Circle is " << S << std::endl;

Otherwise, the using directive carries over to every file that includes that header, which causes an effect called 'namespace pollution', where you start to get conflicts between the names of functions and classes. The whole purpose of namespaces is to help avoid naming collisions, and unrestricted use of the using directive undermines that. It is OK to use using namespace std; in the main program itself, as it won't leak out to any other parts of the program, but having it in a header or a class implementation file is definitely a Bad Thing.

Second, I would add #include guards to your header file, to protect it from being included more than once.

#ifndef FIRSTHOMEWORK_H
#define FIRSTHOMEWORK_H 1

#include <iostream>

class Circle 
{
// the rest of your header goes here
// ...

};  // end of class Rectangle 

#endif

It isn't really that important for this instance, but it is a good habit to get into.

Third, I would move the actual methods of the three classes to …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

From what the OP is saying, I expect what they want is to replace

string id[MAX_SIZE];
double cmarks[MAX_SIZE];
double fmarks[MAX_SIZE];

with something like this:

struct student_grade
{
    string id;
    double cmarks;
    double fmarks;
};

student_grade students[MAX_SIZE];

This is sensible; not only does it structure the data better, it makes it feasible to sort the structs as a unit, keeping the data for each student together.

I think what they wanted to know is how to access the elements of the array of structs. Fortunately, this is quite easy:

students[this_record_index].id = "d3203032sd1";
students[this_record_index].cmarks = 82.3;
students[this_record_index].fmarks = 73.7;

Simple! I will however, give you a piece of advice: if at all possible, use a std::vector<> instead of a fixed array whenever there is any question of how large the array might have to become.

std::vector<student_grade> students;
student_grade* student;

while (infile.good() && !infile.eof())
{
    student = new student_grade();
    infile >> student.id >> student.cmarks >> student.fmarks;
    if (infile.error())
    {
        break;
    }
    students.push_back(student);
}

The std::vector<> template is more efficient memory-wise, and avoids the possibility of overrunning the array.

ddanbe commented: Great advice! +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Just a quick guess, but on line 59, I think you want to change

MOV CL,INSTR1+1

to

LEA CL,INSTR1+1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

soe win: You may want to read this blog post if you aren't clear about what the Solution folder is and how to work with it. While the post covers an earlier version of Visual Studio, the principles have not changed much.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The reason it isn't printing the rest of the list is because... you don't have it printing the rest of the list. Try the following:

void printBackwards(ListNodePtr currentPtr)
{
    // if list is empty
    if(currentPtr==NULL) {
        puts("List is empty.\n");
        return;
    } // end if
    else if ( currentPtr->nextPtr != NULL ) {
        printBackwards(currentPtr->nextPtr);
        printf("%c --> ", currentPtr->data);   // printing the intermediate data here
    } // end else if
    else {
        puts("\nThe list in reverse is:");
        printf("%c --> ", currentPtr->data);
        puts("NULL");
    }
} // end function printBackwards

In addition, I think you'll find that there is a problem in the insert() function; you never set the newPtr->prevPtr value.

    else { // insert new node between previousPtr and currentPtr  
        previousPtr->nextPtr = newPtr;
        newPtr->nextPtr = currentPtr;
        //  should have "newPtr->prevPtr = previousPtr;" here
    } // end else
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

/me dusts off the boilerplate response for this sort of thing... again:

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic ethics on your …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Now, are you looking for the middle of the ArrayList (that is, the midpoint of the data structure), or the middle of the data set (that is, the median value of the data range)? These are two rather different things.

To get the midpoint of the ArrayList, you need to divide the length of the ArrayList by two:

midpoint = (int) Math.floor(arrylst.length / 2.0);

but there's a catch: if the ArrayList has an odd number of elements, there will be a midpoint, to either side of which will be an equal number of elements, but if it is even, then there won't be an exact midpoint and the two halves will be equal with no added midpoint element. For example:

{1, 4, 7, 11, 13}
       ^ midpoint element

{2, 3, 5, 17, 42, 69}
         ^ midpoint is between two elements

So, if you are writing (for example) a binary search routine, you may need need to determine if the ArrayList's length is even or odd before starting to work out if you have two halves, or two halves plus a midpoint.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Sandro_1: If you don't mind me asking, what is it you are trying to accomplish? I'd guess you were calculating the median of the data set, but you didn't specify that the ArrayList was sorted; if it isn't, then it is hard to see what you would be getting from it. What is the purpose of this?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In some cases, it is, or at least that is what I understand; from what I have heard, the university systems of India and Pakistan, in particular, mandate that Turbo C++ be taught as the only programming system, and base all their educational and testing requirements on it. No other language is permitted in their coursework, except assembly, and no other compilers or editors are to be used either. I have been told that efforts to update the curriculum have been made over the years but have been dismissed out of hand by the educational establishment as unnecessary - they see it as making changes for the sake of change, and consider anything less than 25 years old as a temporary fad.

I am not certain if this is the case in the Phillipines, but it may well be given the number of students from there who are taught in this manner.

The situation strikes me as very much like that which Feynman noted about physics teaching in Brazil in the 1950s - the focus is entirely on testing out of the program, and no real understanding is being imparted or even attempted to be imparted. The sheer number of students of computer science in India in particular means that a fair number of talented programmers do come out of their system, but it seems to be in spite of the system than because of it - much like in the US, though for the opposite set of …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Considering that most of the instructors in question also teach C++ as if it were C - using the stdio functions instead of iostream, not covering classes at all, etc. - I would say this is likely.