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

What lunatic taught you to use goto like that? Or at all, for that matter? If your professor is teaching to write code like that - hell, if you professor even mentioned goto in the first place - you should walk away from that course.

Here's a piece of advice: forget that the keyword goto exists. You should never, ever use it for ordinary flow control. It is far too difficult to debug code that uses it. While goto does have its place in C programming, someone just learning the language shouldn't touch it.

ddanbe commented: Could not agree more! +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Hmmn, tricky. While it is possible to do that, it is more dofficult that you probably expect, and almost certainly not what you actually want anyway.

I expect that the real goal here is to save the user's information - say, their name and a high score - so that it will automagically appear next time the program is run, right? Well, I suppose you could indeed use self-modifying code for it the way you propose, doing so is fraught with peril; you are all too likely to wreck the code that way, ending up with an unusable program or worse one that seems to work at first but has subtle bugs in it.

The more typical solution is to store the user information in a separate data file, which you could then check for at the start of the program and, if it is there, load the data from into the variables. You would do something like this:

from os.path import exists

dataFilePath = "foo.csv"

userInfo = dict()

if exists(dataFilePath):
    with open(dataFilePath, 'r') as infile:
        for data in infile.readlines():
            key, value = data.split(';')
            userInfo[key] = value

    for key in userInfo.keys():
        print('{0}: {1}'.format(key, userInfo[key]))

else:
    userInfo['name'] = input("Enter your name: ")
    userInfo['birth date'] =  input("Enter your data of birth (mm/dd/yyyy): ")
    userInfo['home city'] = input('Enter the city you live in: ')
    with open(dataFilePath, 'w') as outfile:
        for key in userInfo.keys():
            print('{0};{1}'.format(key, userInfo[key]), file=outfile)

THis is a simple example, but should do what you want.

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

Did you read AD's reponse earlier? Even if you had explained the project to us in a comprehensible manner - which you didn't - we don't do homework for people here. Do your work, and when you have a problem, as a question and give us enough information to answer it and we will do what we can to help, but giving you a solution by fiat is not helping you..

In any case, you don't give us enough information to base a solution on. What is 'four bar linkage' etc, and what sort analysis do you need to do? Where is the code for this mystery program you mention? We can't write a program when we don't understand the goals of the project.

As for Turbo C, if your professor is requiring you to use it, walk out of the course and don't look back. Anyone still using a twenty-five year old compiler that was not standards compliant even in its own time is incompetent and should not be teaching anyone anything.

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

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, and actually doing so would be an even bigger breach on …

rubberman commented: What more can be said? :-) +12
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, you may very well already have that version of Python installed. Python is widely used in many Linux distributions, and since Python 3.4 is the current stable version, it is safe to say that if you've kept up with your package updates, you may already have that version. Open a shell and type python --version and see what it says.

What Linux distribution are you using? Most distros have a package manager which allows you to download and install most software from within Linux itself. For Ubuntu, the package manager is Synaptics (actually, it's apt-get, but Synaptic is a graphical front-end for it); in Gentoo, it is Portage; in Red Hat, RPM; and so on. How you would use it depends on the package manager in question.

If you distro's package manager doesn't have a package for Python 3.4 yet, then you'll want to download and install the source distribution. The reason there is no pne-click installer for Linux is because Linux programs are usually distributed as source code; the groups that make the Linux distros create the packages from that. If you go back to the Python website, you'll find the source distribution packages. DOwnload that and follow the instructions for untarring and configuring it.

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

As it happens, there are many answers to the question 'how do I learn how to program?', and which one is most effective to you will depend on how you think and what you want to do.

What is constant in all of them is that you will need to actually write programs, and read programs other have written. Beyond that, though, there is no one size fits all answer.

My personal recommendation is to consider the language you want to learn carefully. Different languages appeal to different people, and some are simply hader to learn than others. C and C++ are both rather advanced, industrial-strength languages with a lot of rough edges and few safeties (from the perspective of a newcomer, at least); while many people start off with them, I would recommend a simpler, more forgiving language as your starting place. Python is a good choice, IMO; my real preference is for Scheme, but that is a bit too unusual for most people, and likely to confuse.

A good book, preferably an eBook so as to be as up to date as possible, is useful, as are online tutorials. The online version of Think Python is as good a place as any to being, I would say. Others will suggest others, and I can't say for sure that this one will work for you, but I would try it first.

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

The general answer is, you can't, at least not meaningfully.

The longer answer is, it is very dependent on the hardware and software in question, both the firmware of the drive and the drivers of the operating system. Even if you were dealing with an isolated case - a single drive running on a dedicated real-time system - the results would depend more on the caching algorithm of the drive controller than the drive's own performance.

In practice, very few operating systems ensure real-time performance or measurement (keeping in mind that 'real-time' means bounded time, not necessarily minimum time). In a general-purpose system such as Windows or the Unices, the use of virtual memory essentially makes predictability impossible.

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

Considering that the last person involved in this thread hasn't been around for half a year, I think you may be a bit late to the party.

In other words, don't resurrect lond-dead threads. We have enough zombies on Daniweb already :)

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

While that would indeed play the file, I'm not sure that this accomplishes quite what the OP had in mind. It sounds as if he intended to actually play the file within the program itself, not shell out to a different program to run it. Also, I didn't want to assume he was running Windows.

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

You are in fact opening the file correctly, but that won't do you much good unless you have a codec to decode the data with, I am afraid. We'd have to know what kind of system you are using (e.g., Windows, Linux, MacOS, FreeBSD, etc.) and what kind of libraries you have, in order to be able to even begin giving you any suggestions.

BTW, MP3 is not an open format, and while most systems have some form of MP3 codec to use, it might be easier if you could use files that are in an open format such as Vorbis or FLAC. I know you may not have a choice in the matter, but if you do, try using Ogg Vorbis.

Mohammed_9 commented: thanks i'll try it. +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You need to alter the InsertItem() function so that, instead of always putting the item at the end of the list, it checks to see if the item is less than the next item in the list.

    void InsertItem(ItemType x) // insert x into the list
    {
        bool moreToSearch; moreToSearch = (location != 0);
        nodeptr z = new  Node;
        z->next = NULL;
        z->data = x;

        if (head != NULL)
        {
            location = head;
            while (location->next != NULL && x > location->data())
            {
                location = location->next;
            }
            z->next = location->next;
            location->next = z; 
            length++;
        }
        else
        {
            head = z;
            length = 1;
        }
    };  

This should work well; after all, it does in the version I wrote while trying to figure out what to recommend, though admittedly I changed an awful lot of your code in doing so. :-)

catastrophe2 commented: thnx, but i got this error when i replaced the function with yours: picture attached in reply +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Which are you more familiar with, and do you have a C++ library for the database engine? Java has standard library support for database work in general (the standard C++ library doesn't have any), but still often needs driver for the specific DBMS. In most cases, the differences in support are negligible. Thus, it becomes (as usual) a matter of 'which do you like better?' and 'what does The Mgt want you to use?'

OTOH, if I could choose, I ditch both in favor of Python.

Oh, all right, what I'd really want to use is some Lisp dialect like Clojure. But what company would allow that? Maybe I'll actually get somewhere once I finish implementing Thelema, but I'm not going to hold my breath.

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

NO.

Don't go hijacking other people's threads. Don't go dropping your homework on us without any context. And most of all, don't go demanding code for a project you are supposed to be doing.

We are a patient and, for the most part, helpful group here. Helping you fix problems with your code is what we are here for. So is helping you improve your programming skills. Helping you cheat isn't part of the deal.

With the attitude you are giving in just this one post, I doubt anyone here will ever respond to you unless you make some contrite apologies right away.

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

The first question I will ask is, how are you representing the matrices? The most common matrix representions in Python would be as a list of lists, or (for constant matrices) a tuple of tuples. However, if you intend more elaborate operations, it may make sense to wrap that in a class. How are you representing them, and why?

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

First off, you should understand that a Python function is not a function in the mathematical sense of a relationship between a set of values n<sub>x</sub> in a domain and a value m in a co-domain. Rather, it is a series of expressions that perform a computation, and may or may not return a value. This can be confusing, if you are coming from a mathematical background.

Also, there is a keyword del in Python that has nothing to do with the three functions variously given that name. You'll want to define your own curl(), gradient() or divergence() function to compute the value in question.

Are the two values x and y actually the vector <x,y>? If so, you would do well to define a vector class, if you know how to. If not, you can use lists to pass the vectors around as a unit. Thus, you would actually define your function as taking three parameters, something like this:

def a(vec, i, j):
    vec[0] = grad(i, x)
    vec[1] = grad(j, y)
    return vec

As I say, though, a class would actually be preferable:

class Vector(Object):
    def __init__(self, x, y):
        self.__x = x
        self.__y = y

    def __str__(self):
        return '<{x},{y}>'.format(x=self.__x, y=self.__y)

    def a(self, i, j):
        x = grad(i, self.__x)
        y = grad(j, self.__y)
        return Vector(x, y)  # return a new vector

    def b(self, i, j):
        # put your function definition here


if __name__ == "__main__":
    vec = Vector(2.0, 7.5)
    new_vec = vec.a(3.3, 4.5)

Of course, this …

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

Guidance, certainly; but source code, no, at least not without you showing the effort you've put into it yourself. Post your design ideas and any code you've written, and we'll advise you as best we can.

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

The short answer is, rand() and srand() (which you should call at the beginning of the program before calling rand() for the time) are in <stdlib.h>, so you need to #include that header in order to get the function prototypes for them.

That having been said, I will add that you don't use any functions from either <conio.h> (which you shouldn't be using anyway) or <process.h> (which is specific to Unix-like systems anyway). Oh, and main() should always be declared int, not void.

On a guess, I figure you are using Turbo C++ 1.01, right? DON'T. It is a twenty-five year old MS-DOS compiler that won't run on modern Windows systems without an emulator such as DosBox, and pre-dates the current C and C++ standards. If your professor is requiring you to use it, walk away from the class and don't look back, because you are being taught things that are going to make it harder for you to learn the right ways to program in the modern world. Try to get as many other students to walk out with you - the only way to get them to change their absurd and outdated policies is to throw them back in their faces. If you have to, learn programming on your own - chances are, you'll do better that way than you would trying to make that class work out for you.

Ancient Dragon commented: nice info about Turbo C +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

To elucidate my earlier post: right now, you have S3 overwriting S5 when you run strcpy1(). You want to declare S5 as a .space of at least 9 bytes (8 plus the zero delimiter), or else have it as a .word (a pointer, in effect) and use system call 9 (memory allocation) to allocate 9 bytes for it. The same is true for S4 and S6 as well, though the sizes will be different. The messages now held by S4, S5, and S6 should be moved to their own locations.

.data
S1: .asciiz "I "
S2: .asciiz "love "
S3: .asciiz "assembly"
S4: .space S4 - S1  # set aside space to hold the three strings concatenated
S5: .space S4 - S3  # set aside enough space for a copy of S3
S6: .space S5 - S4  # set aside enough space for a copy of S4
mesg1: .asciiz "\nOur three strings are:\n"
mesg2: .asciiz "\nThe three strings combined are: "
mesg3: .asciiz "\nWhen string 3 is copied into string 5, string 5 is: "
mesg4: .asciiz "\nWhen string 4 is copied into string 6, string 6 is: "
L1: .asciiz "\nThe length of the first string is: "
L2: .asciiz "\nThe length of string 4 is: "

The sizes may need to be explicitly entered in MARS:

S4: .space 16  # set aside space to hold the three strings concatenated
S5: .space 9   # set aside enough space for a copy of S3
S6: .space 16 …
C-Money commented: I didn't see this post earlier, as I've been working on it. Thanks, I'll try this method. +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As JWenting says, the research is yours to do. We can only give advice.

That having been said, I would start by going over the languages you are already familiar with, and see what relevant libraries are available for each. In most cases, the frameworks in question should work with most languages, given sufficient coaxing, so it probably is a matter of what language you are most fluent in. It is unlikely that you would want to choose an unfamiliar notation for this, though that, again, is your decision to make.

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

For the first line of strlen(), change the code to

 addi $t0, $zero, 1 #initialize count to start with 1 for first character

The problem you are experiencing is likely to be because the $t0 register is not guaranteed to be zeroed out when the program starts. You are also loading the character into $t0 in the second line of code, when you presumably want to put it in $t1:

lb $t1, 0($a0) #load the next character to t1

Finally, the usual practice is to use $v0 and $v1 for the return values of functions. I would recommend changing the program thusly:

.data
S1: .asciiz "I "
S2: .asciiz "love "
S3: .asciiz "assembly"
string: .asciiz "Our three strings are:\n"
S4: .asciiz "\nThe three strings combined are: "
S5: .asciiz "\nWhen string 3 is copied into string 5, string 5 is: "
S6: .asciiz "\nWhen string 4 is copied into string 6, string 6 is: "
L1: .asciiz "\nThe length of the first string is: "
L2: .asciiz "\nThe length of string 4 is: "
.text
main:

#display all three strings first
    li $v0, 4
    la $a0, string
    syscall
    la $a0, S1
    syscall 
    la $a0, S2
    syscall
    la $a0, S3
    syscall
    la $a0, S1 #load address of string
    jal strlen #call string length procedure
    move $a0, $v0
    jal print
    addi $a1, $a0, 0 #move address of string to $a1
    addi $v1, $v0, 0 #move length of string to $v1
    addi $v0, $0, 11 #syscall …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

in the inner loop, you are incrementing i instead of j. This leads to you walking off of the end of the array A, but I would expect it to give a segfault, not a stack overflow. How odd.

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

I would recommend using the new operator rather than the C-style memory allocation, but that is what it sounds like you're expected to use, yes.

From the sounds of it, the intention is for you to create the first array in main() (or whatever function you are calling prefixAverages() from), then pass it to prefixAverages() as an argument along with the size of the array. You would then use new to allocate the second array.

int *A = new int[n];

Then, after filling A with the computed values, you would return it as an int pointer.

 int* y = prefixAverages(x, SIZE);

Oh, but don't forget to use delete before the end of the program to free the allocated array:

delete[] y;

EDIT: I forgot the square brackets on the delete.

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

mike_2000_17: While that is indeed a solution to the problem as given, I'm not sure it is the answer Labdabeta needs. This has the smell of a shoe or bottle problem to me; I think Labdabeta should possibly reconsider the direction he's taking, if he finds himself needing such an unusual solution. I may be wrong; there certainly are places where a stream might have to serve multiple purposes like this. I am just not certain this is one of them, and would like a broader picture of the problem.

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

A web framework is a set of interconnected libraries and interfaces that allow you to work with web pages in a more structured manner than the default Python library does (actually, in most languages, there isn't any standard library for HTML and HTTP at all; Python has only a very basic one). Typical web frameworks for Python include Django (probably the most widely used), web2py, Zope, and TurboGears.

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

in the line in question:

 sum[M][3] = inputarray[M][3] + inputarray2[M][3];

You are treating inputarray() and inputarray2() as arrays, rather than calling them as functions. The correct syntax would be:

 sum[M][3] = inputarray(M, 3) + inputarray2(M, 3);

BTW, I strongly recommend you get into the practice of indenting your code suitably. The usual practice is to indent one level - three to eight spaces, depending on your indent style - every time you have a block of code that is inside a loop or an if statement. This practice, called 'nesting', is very important. The goal of formatting code is to make the nesting levels explicit in the layout of the program. While in C, it is purely for the benefit of the programmer, it should make reading and editing the code easier, which is why it is important to get into the habit as soon as you can. I recommend reading this article on the subject for further clarification.

Now, as this Wikipedia entry explains, there are several different styles which one can use to indent their code; what is important is not the specific style, but consistency in applying your chosen style. As long as you follow the main rule - indent inside a block, de-dent after the end of a block - you should be able to use the style you are comfortable with, **so long as you are consistent in appyling it*. those two rules are the …

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

I would actually recommend Gnome Sort, as it is a little smaller marginally faster than Bubble Sort, though it is a little harder to understand. The main reason bubble sort is such a topic of fascination for computer scientists is that it appears to be the 'naive' algorithm for sorting, that is to say, it is the one which most people, if asked to sort a list by computer and not given any algorithms to follow, will come up with on their own.

FYI, in case you are wondering, in practice there are no ideal sorting methods that work fastest for all input. Every practical sorting algorithm is sensitive to the order of the original unsorted list, and even where there is a clear difference in the optimal performance (i.e., O(n log n) for the average case of quicksort versus O(n^2) for Bubblesort), the theoretically slower sorting algorithm may perform better in practice, either because of the order of the input, or because the overhead is smaller for smaller inputs.

In theory, the worst 'practical' sorting algorithm is Bogosort, which consists of repeatedly shuffling the list and testing to see if it has randomly entered a sorted state. The average performance for this is O((n-1) n! (that is to say, the number of items in the list minus one, times the product of every number between 1 and the size of the list - a very, very bad performance); the worst case is unbounded (that is …

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

I went to the extraordinary step of setting up Tubo C++ 1.01 in DosBox on my system, and was able to get the following program to run correctly. Thry it an see if it is acceptable to both TC++ and your professor.

#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void Screen_Header();
void Binary2Decimal();
void Octal2Decimal();
void Hexa2Decimal();

int  main()
{
    char key;

    do
    {    
        Screen_Header();

        scanf("%c", &key);
        gotoxy(1,20);
        printf("Press <ENTER> to Continue or Press <ANY KEY> to Exit ");
        key = getch();
    }
    while(key == '\r');

    return 0;
}

void Screen_Header()
{
    char base;

    clrscr();
    gotoxy(1,3);
    printf("Conversion from any base to base 10");
    gotoxy(1,5);
    printf("a - Binary");
    gotoxy(1,6);
    printf("b - Octal");
    gotoxy(1,7);
    printf("c - Hexadecimal");
    gotoxy(1,11);
    printf("Select a base to be converted: ");
    scanf("%c", &base);

    switch(base)
    {
    case 'a':
        Binary2Decimal();
        break;
    case 'b':
        Octal2Decimal();
        break;
    case 'c':
        Hexa2Decimal();
        break;
    default:
        printf("Sorry, %c is not a valid menu option", base);
    }
}


void Binary2Decimal()
{
    int bin2,f2=1,d2=0;

    gotoxy(1,13);
    printf("[BINARY TO DECIMAL CONVERSION]");
    gotoxy(1,15);
    printf("Enter a Binary number: ");
    scanf("%d", &bin2);

    printf("\n");

    while(bin2>0)
    {
        if((bin2%10)==1)
        {
            d2=d2+f2;
        }
        bin2=bin2/10;
        f2=f2*2;
    }
    printf("Decimal equivalent is: %d", d2);
}

void Octal2Decimal()
{
    char oct8[12];
    unsigned long dec8,i8,sum8,len8;

    sum8 = 0;
    gotoxy(1,13);printf("[OCTAL TO DECIMAL CONVERSION]");
    gotoxy(1,15);printf("Enter an Octal number: ");
    scanf("%11s", oct8);
    printf("\n");

    len8 = strlen(oct8);
    for (i8 = 0; i8 < len8; ++i8)
    {
        dec8 = oct8[i8] - '0';  /* get the value of the digit */
        sum8 = (sum8 * 8) + dec8;
    }
    printf("Decimal equivalent is: %u", sum8);
}


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

What you need to see here is that the 'decimal equivalent' is actually a string of characters, for which there may be (in the case of a 64-bit two's-complement integer representation) 19 digits and a sign to represent. Depending on the character encoding, this may mean as much as 80 bytes (in the case of Unicode-32), though the most common encodings (ASCII, Latin-1, and UTF8) will use 1 byte per character for encoding the Arabic numerals.

Few if any CPU instruction sets have any direct support for any fixed character set; and while some (including the ubiquitous x86 and x86-64) have some very basic string manipulation instructions, these generally don't have anything to do with the character encoding - they are mostly limited to things like copying the string from one place in memory to another.

Now, your standard PC has some firmware support for a small number of character encodings, primarily for the use in displaying text on a text-mode screen, but that too is software (just software that is stored in the ROM chips). The conversions done by most language libraries are entirely in software, as they have to be able to handle different encodings. How the conversion would be done varies with the encoding.

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

If you look down the C++ forum page to the previous thread, you'll see that I gave a detailed answer already.

Would you do us all a favor and not create a new thread each time you log in? It is much easier for everyone if you continue the existing conversations rather than jumping to a new one all over the place. Thank you.

Stuugie commented: If I didn't know better I would say john.kane ignored you on this one. +5
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Woooee's advice is spot on, as far as it goes. However, if you are trying to repeat something without knowing how many times to repeat it, what you would want is a while: loop.

pagechoice = '1'
while pagechoice != '0':
    pagechoice = input("Please choose one:")

    #Now it will determine which page you choose.

    if pagechoice == '1':
        print(""" This is page one """)
    elif pagechoice == '2':
        print(""" This is page two """)
    elif pagechoice == '3':
        print(""" This is page three """)
    elif pagechoice == '4':
        print(""" This is page four """)
    elif pagechoice == '5':
        print(""" This is page five """)
    elif pagechoice == '6':
        print(""" This is page six """)
    else:
        print("Sorry, but what you have typed in is invalid,\nPlease try again.")

this will keep asking for a page number until the user enters a zero. On the gripping hand, if you have something where you want to repeat a fixed number of times - say, one time for each member of a list - you can use a for: loop:

for x in ['a', 'd', 'm', 'e', 'h']:
    print(x)

With a for: loop, it will set the index variable (in this case x) to the next member of the list until it reaches the end of the list. So on the first pass, x would equal 'a', on the second, x would equal 'd', and so forth.

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

Unfortunately, you still aren't indenting your code, making it virtually impossible to read the program. Allow me to (once again) run your code through Astyle and format it sensibly:

#include<iostream.h>
#include<conio.h>
#include<stdio.h>


char value;
char t, u, v;
char answer;

void Binary2Decimal()
{
    gotoxy(1,13);
    printf("[BINARY TO DECIMAL CONVERSION]");

    long b2,f2=1,d2=0;
    gotoxy(1,15);
    printf("Enter a Binary number: ");
    scanf("%d", &b2);

    printf("\n");

    while(b2>0)
    {
        if((b2%10)==1)
        {
            d2=d2+f2;
        }
        b2=b2/10;
        f2=f2*2;
    }
    printf("Decimal equivalent is: ", d2);
}

void Octal2Decimal()
{
    gotoxy(1,13);
    printf("[OCTAL TO DECIMAL CONVERSION]");

    long number4,dec7,rem7,i7,sum7;
    gotoxy(1,15);
    printf("Enter an Octal number: ");
    scanf("%o", &number4);

    printf("\n");

    dec7=printf("%d", number4);
    {
        rem7=dec7%8;
        sum7=sum7 + (i7*rem7);
    }
    printf("Decimal equivalent is: %d", number4);
}

void Hexa2Decimal()
{
    gotoxy(1,13);
    printf("[HEXADECIMAL TO DECIMAL CONVERSION]");

    long hex,dec8,rem8,i8,sum8;
    gotoxy(1,15);
    printf("Enter a Hexadecimal number: ");
    scanf("%X", &hex);

    printf("\n");

    dec8=printf("%d", hex);
    {
        rem8=dec8%16;
        sum8=sum8 + (i8*rem8);
    }
    printf("Decimal equivalent is: %d", hex);
}

void main()

{
    do {
        clrscr();
        gotoxy(1,3);
        printf("Conversion from any base to base 10");
        gotoxy(1,5);
        printf("a - Binary");
        gotoxy(1,6);
        printf("b - Octal");
        gotoxy(1,7);
        printf("c - Hexadecimal");
        gotoxy(1,11);
        printf("Select a value to be converted: ");
        scanf("%c", &value);

        switch(value) {
        case 'a':
            Binary2Decimal();
            break;
        case 'b':
            Octal2Decimal();
            break;
        case 'c':
            Hexa2Decimal();
            break;
        default:
            printf("Wrong input");
        }

        gotoxy(1,20);
        printf("Do you want to continue NUMBER CONVERSION?(y/n) ");
        scanf("%c", &answer);
    }

    while(answer == 'y');
    getch();
}

I cannot emphasize this matter enough; the fact that your professor is accepting unformatted code is a disturbing confirmation that she isn't fit to teach programming, IMAO - I would not accept such code at …

ddanbe commented: More than helpfull +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

NO.

This code relies on the old Turbo C++ compiler, and isn't even remotely viable with any modern C++ compiler.

The real answer is, it depends on the operating system you are writing for and the graphics libraries you are using. C++ doesn't not have any standard graphics support, or even console support for that matter; only the very bare-bones stream I/O is part of the standard library. Everything involving things like background is dependent on the graphics software you are using.

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

OK, so what you actually need is a lexical analyzer, also called a tokenizer from it's main mode of operation, which is to break a stream of characters into tokens. There are several discussions of this topic on DaniWeb, if you do a search on 'tokenizer'. You might want to check out this post, for example, as well as the StateMachine class in my own Suntiger Algol compiler.

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

It would help a lot if you told us what was going wrong; while we can surmise a lot from the code, to be as accurate as possible, we would need to know the exact error messages you are getting.

That having been said, I can see three major problems, offhand, two of which would lead to a compile time error, the other to a runtime error.

The first is a common mistake made by many new C++ programmers, which is that you are confusing function prototypes and function calls, and possibly function implementations as well. A function prototype is a description of the function; it gives the name of the function, the return type, and the name and type of its parameters, like so:

double choiceC(double balance, double totalServCharge)

You would place this before any calls to the function are made. The header of a function implementation looks very similar, and in fact must match the prototype, at least as far as the function name and the types are concerned:

double choiceC(double balance, double totalServCharge)
{
   // the body of the function ...
}

This can be before or after the function is used, so long as you have a prototype for the function before the calls. Finally (and this is where you are having trouble), a function call consists of the name of the function and a list of actual parameters (i.e., arguments), but does not include the types of the parameters.

choice(myBalance, …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In C/C++, command-line arguments (AKA shell arguments) are passed through optional parameters to the main() function. These parameters, by convention named argc and argv, are an integer count of the arguments passed to it, and a pointer to an array of char arrays, which hold the string values of the arguments themselves. Under most (but for some reason, not all) systems, argv[0] is the name of the program itself.

For example, you can write a program that echoes its arguments simply by looping on argc:

#include <iostream>

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc; i++)
    {
        std::cout << argv[i] << std::endl;
    }
    return 0;
}

The downside to using shell arguments is that there is no checking for the type or number of arguments passed; thus, you need to check argc to make sure that it is a legitimate number of arguments, then parse the arguments for their values.

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

As sheikh.islampollob said, the language that you use to implement the project is less relevant to the solution than the design of the program is. One thing I will tell you right now is that the project as described will take more than a month to finish correctly; indeed, if it is mission-critical as it sounds, I would allocate a month or more simply to the planning stages, even if I were applying Agile principles to the project.

If I had to make a suggestion regarding the language, I would start by asking what language(s) you are most familiar with; if you aren't fluent in any language, then tha is a showstopper, as a solid grasp of the language you are working in is necessary for any programming work of any sort.

Since it sounds like you are not a professional programmer yourself, and this is a significant professional project, I would delegate the work of programming it to a dedicated software contractor. For a medical application, simply trying to cowboy your way through the project when you aren't an experienced developer yourself is a recipe for disaster.

ddanbe commented: "A recipe for disaster", is mildly spoken +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

How so? Saying it isn't helpful doesn't tell us what would be helpful. Please give us more to go on, if we are to help you.

As I said, the first step here would be to write a function that returns accpets the Celsius value and returns the Fahrenheit value. Before we can do that, though, we need to work out just how to convert a Celsius value to Fahrenheit. As it happens, this part was already given to you:

f = 9 / 5 * c + 32

So, taking this one step at a time, let's see how this works. If you open up the Python interpreter, and enter

c = 0

then enter the formula above, followed by

f

you should get back the value 32.0. OK, then! Now what you need to do is make the function, which would simply be

def celsius2fahr(c):
    return 9 / 5 * c + 32

basically, all we've done is give the formula above a name, celsius2fahr(). To test it, try entering

celsius2fahr(100)

this should give you 212.0 as the result. you now have a way of repeatedly getting a Fahrenheit value from a Celsius value.

I've got to go now, but this should at least move you in the right direction.

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

I would not really be inclined to send you or anyone else here my email, and I doubt anyone else here would either. Public discourse is highly prized here and strongly preferred. In any case, it is likely that only certain parts of the program are failling to compile; posting the relevent code and error messages here would be more fruitful for all involved.

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

Actually, it does say Java, in the second assignment description. I suspect, however, that it was an error - my guess is, they use the same basic assigment in both the C++ and Java courses, and the instructor made a mistake when editing the assignment.

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

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.

And if you think you won't get caught by your professor... think again.

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

Ancient Dragon commented: Great advice :) +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You say that the code compiles without problem, but I can see an extraneous open brace at the top of the code which would be a showstopper. This may simply be an artifact of copying the code to the forum, however.

I recommend you indent your code effectively, according to a style you find aesthetically pleasing and helpful; the specific style doesn't matter much, so long as you apply some sort of indentation, and are consistent in using the same style across the board. Here is your code again, suitably indented in Allman style (sans the extra brace at the top, and the unneeded Microsoft pre-compiled header, and with the modern headers for the remaining ones):

#include <iostream>
#include <cstdio>
#include <cstring>

class inventory
{
private:
    int prodID;
    char prodDescription[20];
    int qtyInStock;

public:
    inventory() //default constructor
    {
        prodID = 0;
        strcpy(prodDescription,"-");
        qtyInStock = 0;
    }

    inventory(int a, char *b, int c) //constructor that initializes a new Inventoryobjects with the values passed as arguments
    {
        prodID = a;
        strcpy(prodDescription,b);
        qtyInStock = c;
    }
};

int main(int argc, char* argv[])
{
    inventory obj(1,"cotton tshirt",4);
    return 0;
}

I assume that you are using Visual C++ for this, given the use of the <stdafx.h> header. Can you tell us the version you are using? The use of the older style headers (e.g., <iostream.h> rather than <iostream>, <stdio.h> instead of <cstdio>) should have raised a warning with any recent versions of the compiler. Do you know what level of warnings …

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

What is happening here is that you are actually calling the input() operation separately each time you are testing for it, which means that if the value of the first entry is not '1' (and note that it is the string '1', not the numeric literal 1), then the value is discarded - you never save it anywhere. Then, when you get to the first elif clause, you call input() a second time, reading a new value in and testing that. Likewise, the second elif clause reads for a third time, and tests the third value entered.

To avoid this, you want to call input() only once, and save the value in a variable, which you would then test for the three values:

        selection = input()
        if selection == '1':#This is fine.
            print('Okay, you\'re heading to {}\'s tavern.'.format(self.name))  

        elif selection == '2':#This has to be typed in twice.
            print('Okay, you\'re heading to {}\'s inn.'.format(self.name))     

        elif selection == '3':#This has to be typed in three times.
            print('Okay, you\'re heading to {}\'s city hall.'.format(self.name))          

        else:#Four times.
            self.cityMenu()

This should solve the problem nicely.

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

Sounds like a good exercise. What do you have so far?

folabidowu commented: i have done something got confused along the line. am new in C++ +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

can anyone help me to create a program that alows me to make a regular conversation with the computer?

If anyone can, they should contact the Turing Award committee immediately...

Seriously, this isn't anything even remotely trivial. Even a program like an ELIZA-class chatterbot is a sizable project, if you mean to have give it a significant 'phrasebook'. One that can accept a large number of varied inputs, such as Apple's Siri, is something that would take years for both programming and preparing the phrasebook. Even then, it is only a simulation of a real conversation, and tripping it up isn't difficult.

Creating a real, responsively conversational program would probably require solving the hard AI problem - that is to say, it would actually have to be a self-aware, sentient program - which is an ongoing research topic and may not even be possible.

rubberman commented: Great! I missed the chatterbot link... :-) +12
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, what crackers 'hack' is mostly other people's impatience, ignorance and willingness to go along with percieved 'experts' and 'authority figures'. It's called Social Engineering and it is the majority of how crackers circumvent both software and systems. Even software cracks such as program security exploits mostly depends on being able to identify and exploit the weaknesses of the programmers and users, rather than of the code itself.

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

Actually, the stdafx header is specific to Windows, and to Visual Studio in particular. Most other C++ compilers are only going to have the Standard C++ libraries, plus whatever system libraries are used on that OS. Since MacOS X has FreeBSD as it's kernel, XCode should provide most if not all the Unix libraries available to it.

OTOH, if you are looking for an IDE that provides drag-and-drop visual design tools, I'm not sure what you would be looking at. I'm not very familiar with XCode, personally, so I don't know what it comes with, or what extensions are available for it. However, I know that there are versions of Eclipse and NetBeans for the Mac, and while both of those are aimed mainly at Java, both have C++ support as well.

For a basic IDE and compiler, I would try Code::Blocks with GCC. It isn't as full featured, but it is fairly easy to use, and has plenty of support.

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

I would further recommend re-writing the side() function by removing the user interaction, so that the function is responsible solely for computing the desired result:

def pythagorean(first, second):
    ''' pythagorean(float, float) - 
    Function to compute the length of a side of a triangle
    from the lengths of the other two sides.'''
    return math.sqrt((first**2) - (second**2))

# ... later ...

result = pythagorean(3, 4)  # result will equal 5 

The reason for this threefold. First, it simplifies the function, so that it is clearer what it is meant to do. Second, it generalizes the function, making it easier to use in different places for different purposes. Third, it is generally a good idea to separate the code that performs the actual computation from the user interaction, so that it is easier to change either or both of them without interfering with the other; mixing two different operations generally makes for code that is difficult to maintain. Separating the code this way is just a good way of avoiding future issues.

Note also that I added a simple docstring comment to the function. This makes it so that pydoc (the Python documentation tool) can extract the docstring and generate user documentation for the function automatically.

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

ArashVenus: There really isn't any exact replacement for getch(), for the same reason why there wasn't a standard equivalent of getch() to begin with: because 'raw' or unbuffered console I/O isn't portable across different operating systems. The C standard library, and the C++ iostream classes, work exclusively with stream I/O, which does not allow for unbuffered keyboard input. As far as the stream I/O functions are concerned, it is irrelevant whether the input comes from a console, a file, a pipe, or a network socket. While this is a useful abstraction, it makes writing screen manipulation routines harder. The closest equivalent to the conio functions that is even remotely portable would be Curses or its variants, and even then it is mostly aimed at Unix-like systems.

That having been said, the most common use for getch() was to pause the console at the end of the program, so that the window doesn't close. This isn't needed in more recent IDEs like Code::Blocks or the current version of Visual Studio, as they automatically pause the console window when the program is done.

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

OK, let's start with a few issues in your code. First off, main() should always be declared as type int in C++; there are some exceptions to this, but as a rule, void main() is simply incorrect.

Second, you seem to be using an older style of C++ header; with modern C++ (that is, after 1998), the standard library headers should not end with an .h, as they do in C, and C libraries should be pre-pended with a c. Thus, you should have the follow directives instead:

#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>

Note that I removed the reference to <conio.h>; this is not a standard header, but one specific to the older DOS versions of Turbo C++, and should never be used in any new code for any reason. Since you don't seem to actually use it, except to capture the screen, it is safe to simply eliminate this.

I'm guessing that you are using Turbo C++, correct? If you have any choice in the matter, don't. It is now more than 25 years old, and is tied to functions of the DOS operating system which modern Windows systems no longer support (especially with Vista and later). By using Turbo C++, you are shooting yourself in the foot. I know that some schools have standardized on Turbo C++, but I will tell you this right now: you are learning a version of C++ that is nearly 15 years out of date. Get

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

The line between 'helping you finish a project' and 'helping you cheat' is a fine one, at times. However, in this case the Daniweb rules are pretty straightforward:

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

So: Show us what you have done so far, and tell us what you are having difficulty with, and we will assist you. We will not, and cannot, provide you a solution without you showing some effort on your part.

BTW, you should know that the Travelling Salesman Problem is a classic one, with many variations, and is provably NP-complete (meaning that all the known general solutions require non-deterministic polynomial time; any solution in less than exponential time would effectively be a proof that NP = P, which is an open question to date and thought by many to be undecidable). Just so you know.

aroshkhan commented: haha great (Y) +0