PDA

View Full Version : C++ Compiler for Mac? HELP with xcode?




Pages : [1] 2

oxshannon
Jan 5, 2012, 07:35 PM
So I'm totally new to the mac community (got my macbook pro for xmas) and now the semester has started again and Im registered in a first year math course -- introduction to computing with c++. now you guys can probably see where this is going.

basically, I hadone class and my professor gave us a linkto download a c++ compiler for windows, and I emailed him asking about one for Mac, and he told me I would have to search the internet for one as he has no experience with mac. so i did some searching and determined i should download xcode? NOW im still downloading it, but im fairly certain i wont be able to work it. im not a computer programming person, im only taking this course to satisfy my math credit requirements, but i do think it is something i may enjoy once i learn it. im really confused, and my prof wrote the textbook we use himself so i dont really find it to be much help. Honestly, any help would be greatly appreciated.

Thanks.



balamw
Jan 5, 2012, 07:45 PM
For an introductory course, you may want to skip the IDE, i.e. Xcode and use the compiler directly.

You can skip Xcode and install the compilers from here: https://github.com/kennethreitz/osx-gcc-installer

Can you point us to the book? This will let us know a bit more about the style.

B

lloyddean
Jan 5, 2012, 07:47 PM
Having the title of the text book in question will affect the help provided here.

oxshannon
Jan 5, 2012, 07:52 PM
Technically I dont think it would be considered a textbook, its binded by my university and says "Math 1116 - Introduction to Computing with C++ Lecture Notes". So you're saying I don't need xcode? I'm so confused, I swear I'm not dumb but this topic is so new to me and quite confusing :(

also, would it just be "OS X 10.7 Lion: GCC-10.7.pkg" that I download from that link?

balamw
Jan 5, 2012, 07:56 PM
Presuming you are running Lion ;)

It really depends on how the examples are described and set up. If it is really fine tuned for Visual C++ you may find doing it on the Mac more difficult.

B

oxshannon
Jan 5, 2012, 07:59 PM
Presuming you are running Lion ;)

B

Yes I am! I actually got something correct tonight. Lol my "homework" per se was to run a code given to us by my prof (shown below) in the compiler to make sure we can do it. so once i get this downloaded (unfortunately will take forever since I am on residence wireless) -- what should my next step be? if anyone is willing to explain that is :)


#include <iostream>

int main( )
{
std::cout << "Hello world!\n";
return 0;
}


----------

I suppose I could always just use the windows PCs at the library, but that is such a hassle if I could find out how to do it on my mac instead!

lloyddean
Jan 5, 2012, 08:00 PM
Xcode is a development environment. It includes a Text Editor (for writing source code), a C/C++ and ObjectiveC/C++ compiler, a linker and more.

Go ahead and download Xcode. You need the all the compiler and linker no matter what. But you maybe able to get by without learning the IDE, Integrated Development Environment that Xcode also provides.

CHeck back when you start programming you'll get plenty of help going from there.

chown33
Jan 5, 2012, 08:01 PM
Having the title of the text book in question will affect the help provided here.
As would knowing which C++ compiler the prof told the Windows users to download. It's unclear to me whether it's a command-line C++ compiler, a simple GUI/IDE, or a full-featured GUI/IDE.

Context is important, and knowing exactly what the prof expects students to use is an important part of the context.

balamw
Jan 5, 2012, 08:01 PM
Great!

Any chance you could give us some context for that code. This is a fairly typical first step, but it would help to see how your prof surrounds it.

Please wrap any code snippets in CODE tags using the hash mark # button in the edit window.

B

oxshannon
Jan 5, 2012, 08:04 PM
As would knowing which C++ compiler the prof told the Windows users to download. It's unclear to me whether it's a command-line C++ compiler, a simple GUI/IDE, or a full-featured GUI/IDE.

Context is important, and knowing exactly what the prof expects students to use is an important part of the context.

The file name was VC2005.exe, so im assuming microsoft visual c++? that's what came up when i googled it.
im starting to think im over my head in this.

----------

Great!

Any chance you could give us some context for that code. This is a fairly typical first step, but it would help to see how your prof surrounds it.

Please wrap any code snippets in CODE tags using the hash mark # button in the edit window.

B

Um it's just the first example we were given, all it says concerning it is that the output should be Hello world! Not much else is given.

balamw
Jan 5, 2012, 08:07 PM
The file name was VC2005.exe, so im assuming microsoft visual c++? that's what came up when i googled it.
im starting to think im over my head in this.

Don't Panic. At this level you'll be fine.

It would have been much worse if the "Hello World!" example used a Windows specific dialog box mechanism. (Don't read this (http://wiki.originlab.com/~originla/wiki/index.php?title=Create_a_Hello_World_Dialog_(User-Interface_Development))).

B

oxshannon
Jan 5, 2012, 08:09 PM
Don't Panic. At this level you'll be fine.

It would have been much worse if the "Hello World!" example used a Windows specific dialog box mechanism. (Don't read this (http://wiki.originlab.com/~originla/wiki/index.php?title=Create_a_Hello_World_Dialog_(User-Interface_Development))).

B

Thanks. I just wish I understood the concept a bit more, like I said my textbook isnt quite a textbook, it seems its just lecture notes so it doesnt really give any context.

KnightWRX
Jan 5, 2012, 08:10 PM
Yes I am! I actually got something correct tonight. Lol my "homework" per se was to run a code given to us by my prof (shown below) in the compiler to make sure we can do it. so once i get this downloaded (unfortunately will take forever since I am on residence wireless) -- what should my next step be? if anyone is willing to explain that is :)

#include <iostream>

int main( )
{
std::cout << "Hello world!\n";
return 0;
}

Just copy/paste it in your favorite editor and save it with a .cpp extension. Then, it's just a matter of compiling/linking it with the GCC you installed. For C++, you'll want to use the g++ executable as so for a simple compile/link operation. This is all done under Terminal (Applications -> Utilities -> Terminal) :

$ pwd
/Users/username
$ cd dir_where_file_is_stored
$ g++ -Wall -o test test.cpp
$

If the command just returns to the prompt like my example did, then it's because it compiled fine. You should have an executable named test (the -o parameter specifies the executable name to create). You can run it as so :

$ ./test
Hello world!
$

You might want to learn a thing or two about Makefiles and GNU make (http://www.gnu.org/software/make/manual/html_node/index.html) for more complicated projects. If your code is strewn about multiple files, you have to first compile each into object code one by one (one file at a time) and then link them together manually. Makefiles and GNU make automate this process.

EDIT : Or just get Xcode which should hide a lot of this complexity.

balamw
Jan 5, 2012, 08:13 PM
You might want to learn a thing or two about Makefiles and GNU make (http://www.gnu.org/software/make/manual/html_node/index.html) for more complicated projects.

Even for simple projects!

I've started using make test instead of your g++ command above from an earlier version of this thread. :p


----------

EDIT : Or just get Xcode which should hide a lot of this complexity.

But adds more things to learn (a different kind of complexity) if you aren't already familiar with an IDE.

B

oxshannon
Jan 5, 2012, 08:16 PM
I'm not even sure I'll know how to run this once it's installed. I'm really lost lol. Like I said I'm completely new to mac and between xmas and now have not had a lot of time to figure things out.

also is terminal equivalent to command prompt? im assuming

VPrime
Jan 5, 2012, 08:29 PM
To those saying don't use xcode do it all through terminal.. I disagree.
Sure that makes sense as a step for someone trying to get into computer science, or programming as a future career.
But if all you're trying to do is pass a class then I wouldn't bother with the terminal.
In xcode it is as simple as starting a new project (first prompt when it starts up).
Tell it you want to make a mac OSX command line application (in this case)
Then paste the code from your book into the text window. And click the button with a "play" icon on it (build and run).
Your results will be at the bottom in the console window.

Will take you all of 5 minutes to get going. This way you won't fall behind with your class.
Here is a video for Xcode 3.. The interface is slightly different, but you should be able to follow along.
http://www.youtube.com/watch?v=ZU_MT9PwKkk

edit:
Xcode 4 video..
http://www.youtube.com/watch?v=SGwS9XNal4I

mobilehaathi
Jan 5, 2012, 08:37 PM
To those saying don't use xcode do it all through terminal.. I disagree.
Sure that makes sense as a step for someone trying to get into computer science, or programming as a future career.
But if all you're trying to do is pass a class then I wouldn't bother with the terminal.
In xcode it is as simple as starting a new project (first prompt when it starts up).
Tell it you want to make a mac OSX command line application (in this case)
Then paste the code from your book into the text window. And click the button with a "play" icon on it (build and run).
Your results will be at the bottom in the console window.

Will take you all of 5 minutes to get going. This way you won't fall behind with your class.
Here is a video for Xcode 3.. The interface is slightly different, but you should be able to follow along.
http://www.youtube.com/watch?v=ZU_MT9PwKkk

edit:
Xcode 4 video..
http://www.youtube.com/watch?v=SGwS9XNal4I

I find that an IDE only complicates things and hides important steps that a newbie really should know. Sure it streamlines a lot for the intermediate and advanced user, but I still think a beginner should start on the command line. Just MHO...

oxshannon
Jan 5, 2012, 08:41 PM
okay ummmm so ive downloaded that file from the link I was given up above.. but i installed it and now I have no idea where it went or whatever. how would i uninstall this? my god im in over my head

lloyddean
Jan 5, 2012, 08:45 PM
Breath. Breath. Breath.

See you're still alive and nothing bad has happened so relax.

oxshannon
Jan 5, 2012, 08:49 PM
i just have no idea what to do now! how would i go about uninstalling this when i am done with it? and more importantly how do i USE it? :confused::confused::confused::confused:

lloyddean
Jan 5, 2012, 09:11 PM
Everyone seems to have dropped out for dinner so I guest I'll give it a go.

Assuming you run the Xcode installer ...

Locate and run the "TextEdit.app" in the "Applications" folder.

Paste your code from above into the blank window and save it to whatever folder you plan to keep your Math programming projects with a name that ends with .cpp. Something along the lines of "MathAssignment1.cpp"

Now run (launch) "Terminal.app" located in Applications/Utilities.

The Terminal is analogous to the Windows command-line. You'll now need to tell the command-line where your "MathAssignment1.cpp" is with the 'cd' (change directory) command.

If you saved the "MathAssignment1.cpp" to your "Desktop" that would be -

cd ~/Desktop

Now type -

clang++ -Wall -o MathAssignment1 MathAssignment1.cpp

Assuming no errors you can run the executable with -

./MathAssignment1

Have fun!

oxshannon
Jan 5, 2012, 09:24 PM
bash: cd~/Desktop: No such file or directory

I did save it to my desktop, and thats what it said?

subsonix
Jan 5, 2012, 09:28 PM
If you are using TextEdit don't forget to set it to plain text.

oxshannon
Jan 5, 2012, 09:33 PM
yep i did

----------

so i think i got it? I hit enter after i typed that last line in and a new file showed up on my desktop. is that all?

subsonix
Jan 5, 2012, 09:33 PM
bash: cd~/Desktop: No such file or directory


You need to have a space in there, cd (change directory) is the command ~/desktop is the path.

edit
so i think i got it? I hit enter after i typed that last line in and a new file showed up on my desktop. is that all?

Sounds like you managed to get it working, never mind.

lloyddean
Jan 5, 2012, 09:34 PM
cd ~/Desktop

Note the space after 'cd'

oxshannon
Jan 5, 2012, 09:37 PM
oh yay i got it. i can calculate the area of a rectangle now using one of the examples he gave us! awesome. so I just need to type those 2 things in everytime? well, change it according to where my .cpp is saved, but the second line will be the -clang thing? and what if there are errors, what does it do?

lloyddean
Jan 5, 2012, 09:39 PM
Pretty much.

Post here if you don't understand the errors and someone will get back to you!

subsonix
Jan 5, 2012, 09:40 PM
and what if there are errors, what does it do?

If there are compile errors, then they will be printed in the terminal and the compilation will fail.

oxshannon
Jan 5, 2012, 09:41 PM
this is awesome. i dont feel like im wandering aimlessly anymore. i will be prepared for my second class it seems! lol
THANKS so much everyone for putting up with my idiocy and being patient :)

lloyddean
Jan 5, 2012, 09:44 PM
The best thing is you're still alive, calm and it didn't hurt much nor very long!

oxshannon
Jan 5, 2012, 09:47 PM
in the middle there it kind of got a bit painful ;)
hey how would i go to a location with spaces? like the rest of my examples are stored in a folder called Math 1116? Should i change that to like, math_1116 or is there a way to deal with the spaces?

mobilehaathi
Jan 5, 2012, 09:51 PM
in the middle there it kind of got a bit painful ;)
hey how would i go to a location with spaces? like the rest of my examples are stored in a folder called Math 1116? Should i change that to like, math_1116 or is there a way to deal with the spaces?
If the folder is on the desktop cd ~/Desktop/Math\ 1116 will get you there. I never put spaces in my folders since it is a bit of a pain to navigate them in the terminal.

lloyddean
Jan 5, 2012, 09:51 PM
cd ~/Desktop/"Math 1116"

mobilehaathi
Jan 5, 2012, 09:53 PM
in the middle there it kind of got a bit painful ;)
hey how would i go to a location with spaces? like the rest of my examples are stored in a folder called Math 1116? Should i change that to like, math_1116 or is there a way to deal with the spaces?

You can also use the tab key to auto-complete! Try it out; it is a real time saver.

oxshannon
Jan 5, 2012, 09:56 PM
oh cool!! thanks guys :-) this is going to be such a rough class i think, im like the only girl its so weird. i guess the next step is to learn how to write these things huh! haha

mobilehaathi
Jan 5, 2012, 09:58 PM
oh cool!! thanks guys :-) this is going to be such a rough class i think, im like the only girl its so weird. i guess the next step is to learn how to write these things huh! haha

It will come in time.:cool:

You can always check back here for any help you might need.

oxshannon
Jan 5, 2012, 10:00 PM
It will come in time.:cool:

You can always check back here for any help you might need.
Yeah I will definitely be doing that! I dont think I will feel comfortable talking to the prof, because I'm not good at understanding people with a thick accent and the whole encounter would just be awkward. The lab instructor seems to be a nice english as a first language lady, so she might be of some assistance! But I will just keep bumping this thread to the top with any questions I have..I wouldnt want to continuously make new threads!

mobilehaathi
Jan 5, 2012, 10:02 PM
Yeah I will definitely be doing that! I dont think I will feel comfortable talking to the prof, because I'm not good at understanding people with a thick accent and the whole encounter would just be awkward. The lab instructor seems to be a nice english as a first language lady, so she might be of some assistance! But I will just keep bumping this thread to the top with any questions I have..I wouldnt want to continuously make new threads!

Separate threads for separate problems are probably better. And the only way to understand your prof better is to talk to him/her!

oxshannon
Jan 5, 2012, 10:09 PM
If you say so, I may end up with a lot of questions! Lol but yeah I guess speerate threads would keep everything concise and organized. Hes one of the profs Im super intimidated by, so I think If I feel I am doing okay I will steer clear. he seems too smart for his own good to be honest.

DESNOS
Jan 6, 2012, 03:05 AM
I would advise at least trying to learn to use Xcode. The fact of the matter is that the command line is generally only used for compiling command-line apps. GUI apps generally require some sort of IDE, at least for designing the GUI, which I assume you will someday intend to do since the command line is only something one uses behind the scenes nowadays... For now though, Xcode can do far more than you need; I suppose it's a matter of what you plan to do with your programming. Even windows programming will be easier if you can get used to IDE programming. IDEs tend to have many similar features.

KnightWRX
Jan 6, 2012, 04:11 AM
I would advise at least trying to learn to use Xcode. The fact of the matter is that the command line is generally only used for compiling command-line apps. GUI apps generally require some sort of IDE, at least for designing the GUI, which I assume you will someday intend to do since the command line is only something one uses behind the scenes nowadays...

Hum, none of what you said here is true. You can compile GUI code from the command line, you can build GUI apps without an IDE, even for designing the GUI. The command line is far more than something one uses behind the scenes nowadays too.

The OP is doing a math class, the command-line is fine for that.

Balamw pointed the OP to a GCC build rather than XCode, that's what the OP installed.

DESNOS
Jan 6, 2012, 04:45 AM
Hum, none of what you said here is true. You can compile GUI code from the command line, you can build GUI apps without an IDE, even for designing the GUI. The command line is far more than something one uses behind the scenes nowadays too.

The OP is doing a math class, the command-line is fine for that.

Balamw pointed the OP to a GCC build rather than XCode, that's what the OP installed.

You misunderstood most of what I said. My point is that generally you use IDEs for GUI development these days, or at least that's what they teach, and I meant in terms of code. You can use command-line tools within code to make your job easier, and it's something I do often. I'm talking about programming here, not computer usage in general.

balamw
Jan 6, 2012, 05:48 AM
My point is that generally you use IDEs for GUI development these days, or at least that's what they teach, and I meant in terms of code.

The OP is in a C++ class, not an Objective-C or GUI class. What kind of GUIness are they going to get into at this point?

The compilers are only <300MB to download vs. ~4GB for Xcode.

Which do you think is more intimidating for a newbie?

B

KnightWRX
Jan 6, 2012, 08:19 AM
The OP is in a C++ class, not an Objective-C or GUI class. What kind of GUIness are they going to get into at this point?

The compilers are only <300MB to download vs. ~4GB for Xcode.


Not to mention copy/pasting commands or typing them up from notes/litterature is much easier than finding that button/checkbox/field that might or might not be there in your particular GUI package's version.

calderone
Jan 6, 2012, 10:15 AM
The OP is in a C++ class, not an Objective-C or GUI class. What kind of GUIness are they going to get into at this point?

The compilers are only <300MB to download vs. ~4GB for Xcode.

Which do you think is more intimidating for a newbie?

B

I don't see how size of a download is proportional to the level of intimidation.

In fact, I would think a typical individual new to programming would find compiling in the command line much more intimidating, assuming no previous conformability with doing tasks in the command line.

However, to go along with what KnightWRX was getting at, IDEs often are too specific making it difficult to do more generalized things and far too forgiving of mistakes.

Starting pure with a text editor and a complier is the best way to learn.

balamw
Jan 6, 2012, 11:23 AM
I don't see how size of a download is proportional to the level of intimidation.

Did you read the OP's posts?

NOW im still downloading it, but im fairly certain i wont be able to work it..

so once i get this downloaded (unfortunately will take forever since I am on residence wireless)



B

subsonix
Jan 6, 2012, 11:46 AM
There is another option to get Xcode, install it from the OS X install disk that came with the computer.

mobilehaathi
Jan 6, 2012, 11:48 AM
There is another option to get Xcode, install it from the OS X install disk that came with the computer.

She may have bought a computer with Lion, in which case she's SOL.

But she already resolved her problem.:)

balamw
Jan 6, 2012, 11:49 AM
There is another option to get Xcode, install it from the OS X install disk that came with the computer.

Unfortunately that doesn't work so well under Lion. Either the machine didn't come with disks (at least the MBAs don't), or the one on disk is the older version (Xcode 3) that isn't really supported for install under Lion.

B

lloyddean
Jan 6, 2012, 11:54 AM
As I recall of 10.7, Lion, Xcode isn't included, in any form, with a new Mac of any type.

I'd like to see the argument stop. She seems nervous enough without all the misinformation being argued. She has something that works from where she started and anything else is more likely to confuse than help.

Wait till her requirements change - if they do.

subsonix
Jan 6, 2012, 11:54 AM
She may have bought a computer with Lion, in which case she's SOL.

But she already resolved her problem.:)

Unfortunately that doesn't work so well under Lion. Either the machine didn't come with disks (at least the MBAs don't), or the one on disk is the older version (Xcode 3) that isn't really supported for install under Lion.

B

In this case it was a macbook pro no? In any case, I just thought I should mention it if the only stumbling block was the actual download. If Lion is shipping with Xcode 3, that is completely backwards.

mobilehaathi
Jan 6, 2012, 12:00 PM
In this case it was a macbook pro no? In any case, I just thought I should mention it if the only stumbling block was the actual download. If Lion is shipping with Xcode 3, that is completely backwards.

My understanding is that no new Macs ship with the DVDs anymore. I bought a MacPro for work a few months ago and it came with bupkis.

subsonix
Jan 6, 2012, 12:11 PM
I bought a MacPro for work a few months ago and it came with bupkis.

Why make something practical if you can prove a point.

mobilehaathi
Jan 6, 2012, 12:13 PM
Why make something practical if you can prove a point.

I don't follow.

balamw
Jan 6, 2012, 12:15 PM
it came with bupkis.

I wasn't sure. The only Lion machine I bought is an MBA. The others were upgraded to Lion, and thus I have Xcode 3 or earlier on disk.

B

subsonix
Jan 6, 2012, 12:18 PM
I don't follow.

I'm sorry should have been more clear. It's my cynical remark on Apples policy if this is true. It would be more practical in terms of maintenance and so forth if the computer shipped with an OS disk. However shipping with nothing proves an aesthetic point as well as telling how progressive you are, look no disks!

mobilehaathi
Jan 6, 2012, 12:19 PM
I'm sorry should have been more clear. It's my cynical remark on Apples policy if this is true. It would be more practical in terms of maintenance and so forth if the computer shipped with an OS disk. However shipping with nothing proves an aesthetic point as well as telling how progressive you are, look no disks!

Ahh, yeah I have to agree with you. :(

firewood
Jan 6, 2012, 12:36 PM
If you download Xcode, but learn to develop C/C++ programs on your Mac using only command-line tools, you will, almost for free, also be learning how to develop programs for most linux servers. This can be a useful skill.

oxshannon
Jan 6, 2012, 01:38 PM
You guys are too funny, I dont understand half of what youre talking about. Too smart, too smart. And yeah my macbook pro didnt come with any disks. i think im good for now for what I need the program for, because as far as i can tell about half the class is learning to write the code stuff, so since the semester endsin april it really wont be that in depth. but like i said if i have any more questions ill be posting here :-)

chown33
Jan 6, 2012, 02:22 PM
You guys are too funny, I dont understand half of what youre talking about. Too smart, too smart.

Occupational hazard.

It's why xkcd is so funny (at least to us).
http://xkcd.com/386/

calderone
Jan 6, 2012, 02:31 PM
Did you read the OP's posts?


B

Again, this is no way links to the intimidation level of using either, which is what you were stating. No where did I dispute that one is larger than the other.

balamw
Jan 6, 2012, 02:33 PM
Occupational hazard.

Good thing we didn't get into a discussion about which editor real programmers use (http://xkcd.com/378/). :p

B

thundersteele
Jan 7, 2012, 12:38 AM
Good thing we didn't get into a discussion about which editor real programmers use (http://xkcd.com/378/). :p

B

Vim of course!

mobilehaathi
Jan 7, 2012, 12:42 AM
Vim of course!

Must.....resist.....nerd.....war....

lloyddean
Jan 7, 2012, 10:58 AM
Let me get this straight. After spending 30+ years programming to become a somewhat competent programmer I could've become a "real" programmer by simply using 'VIM'.

Where we're you when I needed help?

KnightWRX
Jan 7, 2012, 11:40 AM
Let me get this straight. After spending 30+ years programming to become a somewhat competent programmer I could've become a "real" programmer by simply using 'VIM'.

That's not what he said. Real programmers use VIM but all VIM users aren't real programmers. It's a Squares and Rectangles thing. ;)

lloyddean
Jan 7, 2012, 12:10 PM
Let me get this straight. You're telling me most 'VIM' users aren't "real" programmers they're just posers!

Wait a minute, that cant be right - this must be a rumors forum of some kind.

KnightWRX
Jan 7, 2012, 01:54 PM
Let me get this straight. You're telling me most 'VIM' users aren't "real" programmers they're just posers!

Wait a minute, that cant be right - this must be a rumors forum of some kind.

All Squares are rectangles but not all rectangles are squares. It doesn't mean all other rectangles are square posers, just that they aren't square.

Obviously, you're not a VIM user and you'd have grasp was I was talking about. :D

lloyddean
Jan 7, 2012, 02:09 PM
Each platform I've programmed on has it's own native editor. I can't afford to be that partial.

mobilehaathi
Jan 7, 2012, 02:53 PM
Each platform I've programmed on has it's own native editor. I can't afford to be that partial.

I can't tell if you're incredibly dense and can't take a joke or if you've perfected the subtle art of trolling.

lloyddean
Jan 7, 2012, 04:20 PM
Neither! I'm in a lot of pain and it gives me some small amount of amusement.

oxshannon
Jan 29, 2012, 05:37 PM
I'm just going to post this question here and hope for a response, haha.
I'm trying to write a code that converts CAD to USD (assuming 1CAD = 0.98USD) but for some reason that I can't figure out, it isn't working..Here's the code:


#include <iostream>
using namespace std;

#include <iomanip>
using std::setprecision;

int main ()
{
double USD = 0, CAD = 0;

cout << setprecision (2) << fixed;

cout << "Enter the amount of CAD: ";
cin >> CAD;

CAD = (0.98 * USD);
cout << "$" << CAD << " CAD is equal to $" << USD << " USD" << endl;

return 0;

}

So yeah any push in the right direction would be awesome!

lloyddean
Jan 29, 2012, 06:12 PM
cin >> CAD;

CAD = (0.98 * USD);


You get CAD then overwrite it with the following calc.
Anything times zero, which is what you set USD too, is equal to zero.

mobilehaathi
Jan 29, 2012, 06:13 PM
What do you expect

CAD = (0.98 * USD);


to do?

oxshannon
Jan 29, 2012, 06:25 PM
cin >> CAD;

CAD = (0.98 * USD);


You get CAD then overwrite it with the following calc.
Anything times zero, which is what you set USD too, is equal to zero.

yeah i figured it was something like that i just dont know how to alter it

mobilehaathi
Jan 29, 2012, 06:29 PM
yeah i figured it was something like that i just dont know how to alter it

CAD = (0.98 * USD);

Will take the contents of USD, multiply it by 0.98, and store it in CAD. Is that what you want?

oxshannon
Jan 29, 2012, 06:32 PM
CAD = (0.98 * USD);

Will take the contents of USD, multiply it by 0.98, and store it in CAD. Is that what you want?

Yeah I think so.. I just have to write a code tht converts CAD to USD..which would be the opposite of what you just said I think.

mobilehaathi
Jan 29, 2012, 06:34 PM
Yeah I think so.. I just have to write a code tht converts CAD to USD..which would be the opposite of what you just said I think.

How do you convert CAD into USD?

oxshannon
Jan 29, 2012, 06:35 PM
How do you convert CAD into USD?

my professor gave us that 1CAD = 0.98USD was what we should use, even though its not up to date

mobilehaathi
Jan 29, 2012, 06:36 PM
my professor gave us that 1CAD = 0.98USD was what we should use, even though its not up to date

And so if I gave you 100 CAD, how would you convert that into USD?

oxshannon
Jan 29, 2012, 06:38 PM
And so if I gave you 100 CAD, how would you convert that into USD?

um multiply 100CAD by 0.98?

mobilehaathi
Jan 29, 2012, 06:39 PM
um multiply 100CAD by 0.98?

Yes, so in code you'd want to take the number of CAD multiply by 0.98 and store the result in a new variable. How would you write that in code?

oxshannon
Jan 29, 2012, 06:41 PM
Yes, so in code you'd want to take the number of CAD multiply by 0.98 and store the result in a new variable. How would you write that in code?

ugh i dont know. this class is going to be the death of me.

0.98 * CAD = USD? :confused:

mobilehaathi
Jan 29, 2012, 06:43 PM
ugh i dont know. this class is going to be the death of me.

0.98 * CAD = USD? :confused:

Ok, you have the math equation written correctly, but how does the assignment operator (=) work in C? Can you store the number 5 in the variable x by writing

5 = x;


?

lloyddean
Jan 29, 2012, 06:58 PM
double USD = 0, CAD = 0;
cin >> CAD;
CAD = (0.98 * USD);


Again - you ask the user to give a value for CAD.

Then you assign the result back into CAD with:

CAD = (.98 * USD)

... or ...

CAD = (.98 * 0)

... resulting in ...

CAD = 0

A little Algerbra should allow you to figure this out.

oxshannon
Jan 29, 2012, 07:01 PM
Ok, you have the math equation written correctly, but how does the assignment operator (=) work in C? Can you store the number 5 in the variable x by writing

5 = x;


?

so that would be x = 5; am i right?

----------


double USD = 0, CAD = 0;
cin >> CAD;
CAD = (0.98 * USD);


Again - you ask the user to give a value for CAD.

Then you assign the result back into CAD with:

CAD = (.98 * USD)

... or ...

CAD = (.98 * 0)

... resulting in ...

CAD = 0

A little Algerbra should allow you to figure this out.

REason number 1 why I took a programming course as my math elective: i suck at algebra.

can i set it so that USD > 0? is it possible to just replace the equals sign with >? SO CONFUSING

mobilehaathi
Jan 29, 2012, 07:07 PM
so that would be x = 5; am i right?

Yes, so you assign a value to a variable by putting the variable on the left and the value on the right.

Now you've read in the number of canadian dollars and stored it in CAD. You know that to convert to us dollars you need to multiply CAD by 0.98. So you want to take that result and store it in your USD variable.

So, convert my words into code. You know how to do it!

oxshannon
Jan 29, 2012, 07:12 PM
Yes, so you assign a value to a variable by putting the variable on the left and the value on the right.

Now you've read in the number of canadian dollars and stored it in CAD. You know that to convert to us dollars you need to multiply CAD by 0.98. So you want to take that result and store it in your USD variable.

So, convert my words into code. You know how to do it!

unfortunately i do not. :( my life sucks

----------

sweet baby jesus i think i got it.

----------


#include <iostream>
using namespace std;

#include <iomanip>
using std::setprecision;

int main ()
{
double USD, CAD;

cout << setprecision (2) << fixed;

cout << "Enter the amount of CAD: ";
cin >> CAD;

while (USD != 0)
CAD = 0.98 * USD;
USD = 0.98 *CAD;

cout << "$" << CAD << " CAD is equal to $" << USD << " USD" << endl;

return 0;

}

mobilehaathi
Jan 29, 2012, 07:15 PM
unfortunately i do not. :( my life sucks

Yes you do. You have written

CAD = (0.98 * USD);

which multiplies the value of USD by 0.98 and stores it in CAD. You want to multiple the value of CAD by 0.98 and store it in USD. How do you do that?

----------


[/COLOR]sweet baby jesus i think i got it.

----------


#include <iostream>
using namespace std;

#include <iomanip>
using std::setprecision;

int main ()
{
double USD, CAD;

cout << setprecision (2) << fixed;

cout << "Enter the amount of CAD: ";
cin >> CAD;

while (USD != 0)
CAD = 0.98 * USD;
USD = 0.98 *CAD;

cout << "$" << CAD << " CAD is equal to $" << USD << " USD" << endl;

return 0;

}


You don't need what I've bolded.

oxshannon
Jan 29, 2012, 07:17 PM
Yes you do. You have written

CAD = (0.98 * USD);

which multiplies the value of USD by 0.98 and stores it in CAD. You want to multiple the value of CAD by 0.98 and store it in USD. How do you do that?

----------



You don't need what I've bolded.


aw yay! thank you so much for your help i cant believe i was being that dumb.

mobilehaathi
Jan 29, 2012, 07:19 PM
aw yay! thank you so much for your help i cant believe i was being that dumb.

You'll get the hang of it.;)

oxshannon
Jan 29, 2012, 07:33 PM
You'll get the hang of it.;)

its literally like learning a whole new language!
im going to ask you a quick question while youre here..
the problem says "Write a C++ program to display the following sum:
4 + 8 + 12 + 16 + 20 + 24 +...+ 404

i dont understand how to get it to output as that, this is as close as i came:


#include <iostream>
using namespace std;
int main ()
{
int x = 4;
while ( x <=404 )
{
cout << x << endl;
x += 4;
}
return 0;
}


which obviously just displays every 4th number up to 404

----------

its literally like learning a whole new language!
im going to ask you a quick question while youre here..
the problem says "Write a C++ program to display the following sum:
4 + 8 + 12 + 16 + 20 + 24 +...+ 404

i dont understand how to get it to output as that, this is as close as i came:


#include <iostream>
using namespace std;
int main ()
{
int x = 4;
while ( x <=404 )
{
cout << x << endl;
x += 4;
}
return 0;
}


which obviously just displays every 4th number up to 404

ACtually i think this works..

#include <iostream>
using namespace std;
int main()
{
int sum = 0;
for (int x = 4; x<=404; x+=4)
sum += x;

cout << "Sum equals " << sum << endl;

return 0;
}

yay me?

mobilehaathi
Jan 29, 2012, 07:36 PM
its literally like learning a whole new language!
im going to ask you a quick question while youre here..
the problem says "Write a C++ program to display the following sum:
4 + 8 + 12 + 16 + 20 + 24 +...+ 404

i dont understand how to get it to output as that, this is as close as i came:


#include <iostream>
using namespace std;
int main ()
{
int x = 4;
while ( x <=404 )
{
cout << x << endl;
x += 4;
}
return 0;
}


which obviously just displays every 4th number up to 404

----------



ACtually i think this works..

#include <iostream>
using namespace std;
int main()
{
int sum = 0;
for (int x = 4; x<=404; x+=4)
sum += x;

cout << "Sum equals " << sum << endl;

return 0;
}

yay me?

See, you're getting the hang of it!

oxshannon
Jan 29, 2012, 07:49 PM
yayyyyyy

chrono1081
Jan 29, 2012, 08:13 PM
Programming takes practice and dedication, but it'll come with time. Who knows maybe you'll end up really liking it and become a computer programmer ;)

oxshannon
Jan 30, 2012, 09:49 AM
Programming takes practice and dedication, but it'll come with time. Who knows maybe you'll end up really liking it and become a computer programmer ;)
mmm im unsure about that, but you never know! haha i just like the moment of glory when i run something and theres 0 errors and it actually does what i want

mobilehaathi
Jan 30, 2012, 09:55 AM
mmm im unsure about that, but you never know! haha i just like the moment of glory when i run something and theres 0 errors and it actually does what i want

Hehehe, welcome to programming!

danwilliams
Jan 30, 2012, 01:50 PM
mmm im unsure about that, but you never know! haha i just like the moment of glory when i run something and theres 0 errors and it actually does what i want

Having been a software developer for the last 20 years, I can safely say that you have just done one of the hardest things in programming. You completed your first few assignments. And (bonus points) you got a rush at that "aha" moment of when it compiled and worked.

One of the comments by you earlier was that you were "not good at algebra". Just realize this is a justification for not trying or giving up. You have just proven to yourself (and us) that you DID NOT GIVE UP. All of us on this thread can attest that we have been in the same exact position you were just in earlier in our careers. We too did not give up. And we too came up with justifications to give up. "It's too hard." "I suck at writing." "I hate math." "I am an artist." "I am a lover not a fighter." "I hate it." etc...

Hang in there. With time and the effort you just showed, it will get easier.

chrono1081
Jan 30, 2012, 03:59 PM
I remember when I was learning my biggest issue was with classes. I was so confused by them! The syntax was weird, I didn't get what purpose they served, and the example I was given was awful.

After some digging I found a tutorial on them that didn't try and impress the reader by showing all kinds of bells and whistles but instead showed a basic class, then it clicked and now I can't imagine never creating classes.

You will run in to many scenarios like that in programming but with a bit of digging you'll find examples that work for you and whatever you are trying to understand will click and you'll be on your way to the next concept.

oxshannon
Jan 30, 2012, 05:09 PM
wow you guys are so nice :cool:thanks a lot guys, haha im trying so hard, but my professor doesnt speak a lick of english so all he does is write programs on the board and cant really explain them and if you have specific questions its impossible to get an answer. i find that i learn a lot more in lab for two reasons, my lab instructor is a nice english speaking lady and shes very hands on (the whole point of the lab, i guess) i do enjoy it but it gets so frustrating!

chrono1081
Jan 30, 2012, 07:18 PM
wow you guys are so nice :cool:thanks a lot guys, haha im trying so hard, but my professor doesnt speak a lick of english so all he does is write programs on the board and cant really explain them and if you have specific questions its impossible to get an answer. i find that i learn a lot more in lab for two reasons, my lab instructor is a nice english speaking lady and shes very hands on (the whole point of the lab, i guess) i do enjoy it but it gets so frustrating!

One thing that may help is make sure when you look at his programs, that you can comment what every line of code is doing. If you can't, or are stuck on a line make sure you either come here or ask someone for help.

Its a pain but commenting each line of code when learning can really help solidify the ideas.

oxshannon
Jan 31, 2012, 07:20 PM
i more or less understand a code when it is given to me.. just like when im givin a problem and have to write a code, it takes me about 5 times to do it before i do it successfully (or i cant get it at all!) theres just so many options haha but i got a 19/20 on my first assignment so thats a good start

lloyddean
Jan 31, 2012, 07:29 PM
Think, practice, loop ...

Was yesterdays task the second assignment?

oxshannon
Jan 31, 2012, 07:36 PM
Think, practice, loop ...

Was yesterdays task the second assignment?

yup. well those two codes were 2/3 i had to do, then theres short answer types (determine the errors etc) and multiple choice type. i have another question where i have to add 4% a year on to 2500 for 6 years. i think i can manage that one myself.. its not due until feb 7th but im a keener haha

lloyddean
Jan 31, 2012, 07:44 PM
Well keep in mind school is about learning to think and learning how to learn.

Just keep at it and you'll come to enjoy your new found abilities to solve problems instead of panicking when confronted by them.

Oh, and congratulations!

oxshannon
Jan 31, 2012, 07:47 PM
Well keep in mind school is about learning to think and learning how to learn.

Just keep at and you'll come to enjoy your new found abilities to solve problems instead of panicking when confronted by them.

Oh, and congratulations!

hahahaha i know, this stuff is just so different than anything else ive done in my university career to date yano? and thank you! my midterm is 2 weeks from today so im going to buckle down and try to learn what we were taught so far really well :o:o

mobilehaathi
Jan 31, 2012, 07:54 PM
hahahaha i know, this stuff is just so different than anything else ive done in my university career to date yano? and thank you! my midterm is 2 weeks from today so im going to buckle down and try to learn what we were taught so far really well :o:o

and remember you can always come back for questions.....:)

oxshannon
Feb 1, 2012, 10:13 AM
lol you guys dont have to tell me twice.. ill be here. haha im going to attempt that last program now.. any suggestions on which loop to use?


14 A country club, which currently charges $2,500 per year for membership, has announced it will increase its membership fee by 4% each year for the next six years. Write a program that uses a loop to display the projected rates for the next six years. Sample output:
Membership for year 1: $aaaa.aa
….
Membership for year 6: $ffff.ff

lloyddean
Feb 1, 2012, 10:45 AM
'for(;;) {}' and 'while() {}' are very similar but only happen if the initial condition is non false. While 'do {} while()' happens at least once and will repeat only if the condition is non false.

Personal preferences really ...

oxshannon
Feb 1, 2012, 02:29 PM
okay ummm i think i got it, and it outputs fine, except that for the last two outputs, my calculations had me rounding up and the outputs rounded down, or vice versa i dont remember exactly. is there anyway to fix this or what? im going to post the code here, and if theres anything unnecessary that i dont need, could someone let me know :)?


#include <iostream>
using namespace std;

#include <iomanip>
using std::setprecision;

int main ()
{
double sum = 0, membership = 2500;

cout << setprecision (2) << fixed;

for (int year = 1; year <=6; year++)
{
membership = membership * 1.04;
sum = membership;
cout << "Membership for year " << year << " is $" << sum << endl;
}

return 0;
}

mydogisbox
Feb 1, 2012, 02:52 PM
#include <iostream>
using namespace std;

#include <iomanip>
using std::setprecision;

int main ()
{
double sum = 0, membership = 2500;

cout << setprecision (2) << fixed;

for (int year = 1; year <=6; year++)
{
membership = membership * 1.04;
sum = membership;
cout << "Membership for year " << year << " is $" << sum << endl;
}

return 0;
}
[/QUOTE]

Two things:

1. Do you want to add the 6% on for the first year? If not then you will need to move the membership = membership * 1.04 to after your cout statement.
2. It looks like you copied your previous program and retained some of it's logic. Think about what "sum" did in your previous program and check if it's still needed in this one.

oxshannon
Feb 1, 2012, 02:54 PM
That's what I wasn't really sure about.. like its initially 2500, so 4% added on would be 2600 dollars for year one, right?

"A country club, which currently charges $2,500 per year for membership, has announced it will increase its membership fee by 4% each year for the next six years. Write a program that uses a loop to display the projected rates for the next six years. Sample output:
Membership for year 1: $aaaa.aa
….
Membership for year 6: $ffff.ff"

is the question and i find it's kind of vague..


double membership = 2500;

cout << setprecision (2) << fixed;

for (int year = 1; year <=6; year++)
{
membership = membership * 1.04;
cout << "Membership for year " << year << " is $" << membership<< endl;
}

return 0;


would work right? realzing i dont need sum..im silly sometimes

mydogisbox
Feb 1, 2012, 02:59 PM
That's what I wasn't really sure about.. like its initially 2500, so 4% added on would be 2600 dollars for year one, right?

"A country club, which currently charges $2,500 per year for membership, has announced it will increase its membership fee by 4% each year for the next six years. Write a program that uses a loop to display the projected rates for the next six years. Sample output:
Membership for year 1: $aaaa.aa
….
Membership for year 6: $ffff.ff"

is the question and i find it's kind of vague..

...

would work right? realzing i dont need sum..im silly sometimes

Exactly right! sum isn't needed.

For the question itself I would interpret that to mean that you need to have a year "0" which is now and then there will be six years following that where the cost will increase. It is rather vague however, so I could be wrong.

oxshannon
Feb 1, 2012, 03:00 PM
Exactly right! sum isn't needed.

For the question itself I would interpret that to mean that you need to have a year "0" which is now and then there will be six years following that where the cost will increase. It is rather vague however, so I could be wrong.

yay me! hmm yeah i know what you mean, maybe ill ask around in class and see what other people interpreted it as, im sure its not that big of a deal either way since the point of the question is to complete the code for it, which i did so. thank you :o:o

oxshannon
Feb 3, 2012, 08:43 AM
guys im kind of confused on when i need to initialize a variable to 0... and what the difference is between = and ==? any tips?

balamw
Feb 3, 2012, 08:53 AM
guys im kind of confused on when i need to initialize a variable to 0... and what the difference is between = and ==? any tips?

Just my $0.02.

It's generally a good idea to initialize variables, whether you do it to zero or some other initial value depends on the variable.

In C related languages:

= is assignment, put the value on the right into the variable on the left

== is comparison, compare the two sides and let me know if they are equal.

This is why you will see a lot of experienced coders doing comparisons like:

if (0 == myNumber) ...
as putting the constant on the left will have the compiler help you with an error if you inadvertently left out a "=".

B

mobilehaathi
Feb 3, 2012, 08:54 AM
guys im kind of confused on when i need to initialize a variable to 0... and what the difference is between = and ==? any tips?

If you don't initialize a variable, it will have some random value that was in that segment of memory before.

= is assignment. You use this to assign values to variables. == is a Boolean operation which evaluates equivalency. So, x = y, assigns the value of y to x, whereas x == y asks if x and y are equal and will evaluate to either 1 or 0 (true or false).

oxshannon
Feb 3, 2012, 08:58 AM
ahhhhh okay. simple as that haha thank you

oxshannon
Feb 4, 2012, 02:28 PM
im fuzzy on the difference between post incrememnt and pre increment... the examples he used to demonstrate the differencedont make much sense! any help pals?

mobilehaathi
Feb 4, 2012, 02:38 PM
im fuzzy on the difference between post incrememnt and pre increment... the examples he used to demonstrate the differencedont make much sense! any help pals?

Try running this code and looking at the output. Can you explain what seems to be happening?:)

#include <iostream>

using namespace std;

int main (int argc, char* argv[])
{
int a = 1, b = 1, x = 0, y = 0;

cout << "a: " << a << "\nx: " << x << endl;
x = ++a;
cout << "a: " << a << "\nx: " << x << endl;

cout << endl;

cout << "b: " << b << "\ny: " << y << endl;
y = b++;
cout << "b: " << b << "\ny: " << y << endl;

return 0;
}

lloyddean
Feb 4, 2012, 02:50 PM
With post decrement/increment the value is evalutated then modified.

With pre decrement/increment the value is modified then evaluated.

Demonstration:


int main()
{
int loop_count;

loop_count = 1;
while ( counter-- )
{
std::cout << "In \'loop1\'!" << std::endl;
}

loop_count = 1;
while ( --counter )
{
std::cout << "In \'loop2\'!" << std::endl;
}

return 0;
}

oxshannon
Feb 5, 2012, 01:34 PM
i understand it more so now i think.. its hard to wrap my head around though haha so like when it is evaluated, then modified, if x = 0 and then it is evaluated THENmodified, would it output say x = 1 the next time? CONFUSE

mobilehaathi
Feb 5, 2012, 01:48 PM
i understand it more so now i think.. its hard to wrap my head around though haha so like when it is evaluated, then modified, if x = 0 and then it is evaluated THENmodified, would it output say x = 1 the next time? CONFUSE

Let's say a = 1, and x = 0.

If you wrote x = ++a, a would be incremented THEN assigned to x. So after executing x = ++a, x would equal 2 and a would equal 2.

If you wrote x = a++, a would be assigned to x THEN incremented. So after executing x = a++, x would equal 1 and a would equal 2.

If you take the example of the while loop above (and fix the bugs):

int counter;

counter = 1;
while ( counter-- )
{
std::cout << "In \'loop1\'!" << std::endl;
}

counter = 1;
while ( --counter )
{
std::cout << "In \'loop2\'!" << std::endl;
}


In 'loop2'! will not get output, can you figure out why?

lee1210
Feb 5, 2012, 02:08 PM
i understand it more so now i think.. its hard to wrap my head around though haha so like when it is evaluated, then modified, if x = 0 and then it is evaluated THENmodified, would it output say x = 1 the next time? CONFUSE

Your professor should be the one teaching this, but:

int x = 5;
int a = 0;
int b = 0;
int c = 0;
a = --x;
//a now contains 4, x also contains 4
b = x--;
//b now contains 4, x contains 3
c = --b + a++;
// c contains 7, b contains 3, a contains 5

The pre and post increment/decrement will alter the value stored in the variable they operate on. The issue is when this change occurs relative to the rest of the containing expression. If it is a prefix operator, this happens before the rest of the expression. This means the value used in the containing expression will be the value after the change. With a postfix the expression is evaluated with the original value and the variable is modified afterwards. If the pre or postfix operator appears in expression by itself (on its own line, say) which you use is irrelevant. Try this yourself, a lot. Keep going, documenting what you think will happen then checking what does when you run it. Do this until you know what will happen when you run the code.

-Lee

-Lee

oxshannon
Feb 5, 2012, 07:30 PM
okay i think i got it guys!! thanks :D
my prof asked us to give an output for a code, and its a while loop that has x = 2, x>0 and x+= 3, so obviously it goes on forever and ever and ever, think its appropriate if i just put the first few numbers like 2,5,8,11 and then put "etc?"

mobilehaathi
Feb 5, 2012, 07:48 PM
okay i think i got it guys!! thanks :D
my prof asked us to give an output for a code, and its a while loop that has x = 2, x>0 and x+= 3, so obviously it goes on forever and ever and ever, think its appropriate if i just put the first few numbers like 2,5,8,11 and then put "etc?"

a while loop or a for loop?

KnightWRX
Feb 5, 2012, 07:50 PM
okay i think i got it guys!! thanks :D
my prof asked us to give an output for a code, and its a while loop that has x = 2, x>0 and x+= 3, so obviously it goes on forever and ever and ever, think its appropriate if i just put the first few numbers like 2,5,8,11 and then put "etc?"

Depends on X's type and your platform's size for that type. Also depends if X is signed or unsigned.

oxshannon
Feb 5, 2012, 07:55 PM
a while loop or a for loop?


its a while loop, heres the code fragment:


int x = 2;
while ( x > 0 )
{
cout << “The value of x is: “ << x << endl;
x += 3;
}


and heres the question: 11. What output would be produced by the following 3 problems?


so obviously the output will be:

"The value of x is: 2
The value of x is: 5
The value of x: 8
etc" all the way to forever pretty mch.

so i think its appropriate to simply state the first few outputs as ive done above and then write "etc" or "and so on" or whatever. yes?

mobilehaathi
Feb 5, 2012, 07:56 PM
its a while loop, heres the code fragment:


int x = 2;
while ( x > 0 )
{
cout << “The value of x is: “ << x << endl;
x += 3;
}


and heres the question: 11. What output would be produced by the following 3 problems?


so obviously the output will be:

"The value of x is: 2
The value of x is: 5
The value of x: 8
etc" all the way to forever pretty mch.

so i think its appropriate to simply state the first few outputs as ive done above and then write "etc" or "and so on" or whatever. yes?

Jeez, that's kind of mean to ask for the output of an infinite loop. State the first few outputs and then explicitly say that it is an infinite loop and will continue forever.

oxshannon
Feb 5, 2012, 07:58 PM
Jeez, that's kind of mean to ask for the output of an infinite loop. State the first few outputs and then explicitly say that it is an infinite loop and will continue forever.

hahaha yeah i was like hmmmmmm how do i do this lol thanks!!

KnightWRX
Feb 5, 2012, 08:01 PM
Jeez, that's kind of mean to ask for the output of an infinite loop.

It's not an infinite loop because x is signed. Here's an example of why using chars for obvious reasons :

$ cat test.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char ** argv)
{
char x = 2;
printf("x has a size of %lu bytes or %lu bits if you will\n\n", sizeof(char), sizeof(char) * 8);
printf("x now has a value of %d, loop wants it greater/ equal to 0 and we increment it by 3\n", x);
printf("This should loop forever right ?\n\n");
while(x >= 0)
{
printf("%d ", x);
fflush(stdout);
x += 3;
}
printf("\n\nThe loop broke, because x is now %d\n", x);
return EXIT_SUCCESS;
}
$ gcc -Wall -o test test.c
$ ./test
x has a size of 1 bytes or 8 bits if you will

x now has a value of 2, loop wants it greater/ equal to 0 and we increment it by 3
This should loop forever right ?

2 5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89 92 95 98 101 104 107 110 113 116 119 122 125

The loop broke, because x is now -128

It's a trick question.

EDIT : Even using unsigned ints, since the prof made the condition x > 0 and not x >= 0, there's also a chance that the loop would eventually break. It's even possible to calculate when.

mobilehaathi
Feb 5, 2012, 08:03 PM
Excellent point. It'll overflow at some point, obviously. Man I feel stupid now. :o

Edit: sorry for giving wrong advice oxshannon, I was thinking 'too fast.'

It's not an infinite loop because x is signed. Here's an example of why using chars for obvious reasons :

$ cat test.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char ** argv)
{
char x = 2;
printf("x has a size of %lu bytes or %lu bits if you will\n\n", sizeof(char), sizeof(char) * 8);
printf("x now has a value of %d, loop wants it greater/ equal to 0 and we increment it by 3\n", x);
printf("This should loop forever right ?\n\n");
while(x >= 0)
{
printf("%d ", x);
fflush(stdout);
x += 3;
}
printf("\n\nThe loop broke, because x is now %d\n", x);
return EXIT_SUCCESS;
}
$ gcc -Wall -o test test.c
$ ./test
x has a size of 1 bytes or 8 bits if you will

x now has a value of 2, loop wants it greater/ equal to 0 and we increment it by 3
This should loop forever right ?

2 5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89 92 95 98 101 104 107 110 113 116 119 122 125

The loop broke, because x is now -128

It's a trick question.

oxshannon
Feb 5, 2012, 08:08 PM
soooooooooo what would i put then?
hahaha cuz when i ran the code it was like 30000 last time i looked at it :confused:

mobilehaathi
Feb 5, 2012, 08:11 PM
soooooooooo what would i put then?
hahaha cuz when i ran the code it was like 30000 last time i looked at it :confused:

I'll add three to x until it goes over 32767. At this point it'll overflow, x will be negative, and the loop will stop.

oxshannon
Feb 5, 2012, 08:12 PM
I'll add three to x until it goes over 32767. At this point it'll overflow, x will be negative, and the loop will stop.

confusing.... why 32767?

chrono1081
Feb 5, 2012, 08:12 PM
Ya its screwing up Xcode lol. I can't even see the final output.

I too didn't realize it was a trick question until Knight pointed it out.

oxshannon
Feb 5, 2012, 08:16 PM
my prof is a meanie

KnightWRX
Feb 5, 2012, 08:18 PM
soooooooooo what would i put then?
hahaha cuz when i ran the code it was like 30000 last time i looked at it :confused:

You're in a programming class. The answer should be obvious : cheat to get the result. ;)

$ cat test.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char ** argv)
{
int prevx;
int loopiterations = 0;
int MAX_LOOPS = 4;
int runonce = 1;
int x = 2;
while(x >= 0)
{
if(loopiterations < MAX_LOOPS)
{
printf("The value of x is : %d\n", x);
loopiterations++;
}
if(runonce && loopiterations >= MAX_LOOPS)
{
printf("...\n");
runonce = 0;
}
prevx = x;
x += 3;
}
printf("The value of x is : %d\n", prevx);
printf("The value of x is : %d\n", x);
return EXIT_SUCCESS;
}
$ gcc -Wall -o test test.c
$ ./test
The value of x is : 2
The value of x is : 5
The value of x is : 8
The value of x is : 11
...
The value of x is : 2147483645
The value of x is : -2147483648


You can even know how long the cheat version takes to run :

$ time ./test
The value of x is : 2
The value of x is : 5
The value of x is : 8
The value of x is : 11
...
The value of x is : 2147483645
The value of x is : -2147483648

real 0m3.141s
user 0m3.131s
sys 0m0.005s


3 seconds to give out the answer if you cut off the printing at some point. ;)

mobilehaathi
Feb 5, 2012, 08:18 PM
Actually, on my machine ints are long by default, so they overflow after 2147483647...

KnightWRX
Feb 5, 2012, 08:20 PM
I'll add three to x until it goes over 32767. At this point it'll overflow, x will be negative, and the loop will stop.

ints haven't been 16 bit since the days of the 286 though. ;)

----------

One thing to add : the program as your prof gave you will never print the negative value of X, I added that for style points to show why the loop broke.

mobilehaathi
Feb 5, 2012, 08:22 PM
ints haven't been 16 bit since the days of the 286 though. ;)

Yeah I just realized that.......:o That's what I learned and now I realize I've been wasting key strokes declaring long ints....lol

oxshannon
Feb 5, 2012, 08:26 PM
my brain hurts guys hahahaha

mobilehaathi
Feb 5, 2012, 08:40 PM
my brain hurts guys hahahaha

Numbers are stored in binary form in computers, and each type (int, float, etc.) are given a certain amount of memory in which they are stored. ints are given 32 bits of memory. If they are signed, one bit is reserved for the sign (positive or negative), and this leaves 31 bits left in which to store the number. There are 2^(31) numbers that can be held in 31 bits, and so the highest number that can be held in a signed int is 2^(31)-1 = 2147483647 (subtract 1 because you start at 0). If you don't care about negative numbers, you can declare an unsigned int, and use that extra bit to store more numbers. In this case there are 2^(32) numbers that can be held in 32 bits, and the highest number that can be held in an unsigned int is 2^(32)-1 = 4294967295.

Although, I probably just confused you more.

Edit: I said 32767 earlier because when I learned programming ints were 16 bits......

lloyddean
Feb 5, 2012, 09:07 PM
Sorry to say the answer is NOT a trick question - it's just unresearched so it seems so.

The following code determines at runtime, the only way it can be done really, the maximum value of an (signed) 'int' as it is machine dependent.

So the asnwer will be within -3 of the value returned by 'numeric_limits<int>::max()'.


#include <iostream>
#include <limits>

int main()
{
std::cout << "Minimum value for int: " << std::numeric_limits<int>::min() << std::endl;
std::cout << "Maximum value for int: " << std::numeric_limits<int>::max() << std::endl;

return 0;
}


Hope this helps!

KnightWRX
Feb 6, 2012, 04:06 AM
Sorry to say the answer is NOT a trick question - it's just unresearched so it seems so.

I still qualify it as a trick question in an entry level class, where the students aren't yet accustomed into thinking in terms of computer and memory storage areas.

The following code determines at runtime, the only way it can be done really, the maximum value of an (signed) 'int' as it is machine dependent.

So the asnwer will be within -3 of the value returned by 'numeric_limits<int>::max()'.


#include <iostream>
#include <limits>

int main()
{
std::cout << "Minimum value for int: " << std::numeric_limits<int>::min() << std::endl;
std::cout << "Maximum value for int: " << std::numeric_limits<int>::max() << std::endl;

return 0;
}


Hope this helps!

Why use C++ when he course is on C ?

lloyddean
Feb 6, 2012, 11:00 AM
The better question is why do you think it's C?

Look back over the thread and you'll note her posted code is C++.

gnasher729
Feb 6, 2012, 11:00 AM
its a while loop, heres the code fragment:


int x = 2;
while ( x > 0 )
{
cout << “The value of x is: “ << x << endl;
x += 3;
}


and heres the question: 11. What output would be produced by the following 3 problems?


so obviously the output will be:

"The value of x is: 2
The value of x is: 5
The value of x: 8
etc" all the way to forever pretty mch.

so i think its appropriate to simply state the first few outputs as ive done above and then write "etc" or "and so on" or whatever. yes?

It's quite a horrible trick question. Eventually increasing x by 3 again and again will lead to an overflow, and a signed int overflow produces "undefined behaviour" which means _anything_ can happen.

For example, if you use gcc with highest optimisation, the compiler may figure out that you start with x > 0, the only time you ever change it it gets increased by 3, so clearly x > 0 will always be true and the test (x > 0) can be removed.

mobilehaathi
Feb 6, 2012, 11:18 AM
a signed int overflow produces "undefined behaviour" which means _anything_ can happen.


Most often, however, a raptor will jump out of your computer and maul you.

chown33
Feb 6, 2012, 11:44 AM
Most often, however, a raptor will jump out of your computer and maul you.

But with everything getting smaller these days, it's usually a nano-raptor, which any cat, or even a semi-attentive parrot[1], can easily dispatch. In the old days, a VAX-raptor was a thing to be feared.


[1] as long as it's not stunned or pining for the fjords.

mobilehaathi
Feb 6, 2012, 11:50 AM
But with everything getting smaller these days, it's usually a nano-raptor, which any cat, or even a semi-attentive parrot[1], can easily dispatch. In the old days, a VAX-raptor was a thing to be feared.


[1] as long as it's not stunned or pining for the fjords.

Fair point. I understand that, these days, even a broom and dust-pan can deal with most raptor outbreaks.

KnightWRX
Feb 6, 2012, 12:54 PM
Fair point. I understand that, these days, even a broom and dust-pan can deal with most raptor outbreaks.

We're all OS X users here though, Raptor outbreaks aren't a problem, since we know Unix.

oxshannon
Feb 12, 2012, 07:38 PM
My midterm is tuesday, fellas! I think Im all set :D

mobilehaathi
Feb 12, 2012, 07:42 PM
My midterm is tuesday, fellas! I think Im all set :D

Good luck!

lloyddean
Feb 12, 2012, 08:34 PM
Would you mind sharing the result of your other intermediate homework assignments - grade wise that is.

oxshannon
Feb 13, 2012, 10:41 AM
Would you mind sharing the result of your other intermediate homework assignments - grade wise that is.

well we got 3 of our lab assignments back so far, 10/10 on each one.
and we had 2 homework assignments - 19/20 for my first one and 20/20 on my second one!

@mobilehaathi -- thank you :o

oxshannon
Feb 14, 2012, 05:53 PM
It was quite simple!

oxshannon
Feb 23, 2012, 05:02 PM
hi i need help again. i hit a road block.

i have a question that says "Write a single C++ statement that will print a random number from the set {4,9,14,19,24,29,34}

So i totally thought i could do this.

i figured it would be this:


for (int x = 4; x <=34; x+=5)
cout << (rand()%6+1) * 5 << endl;



and apparently thats not it but um WHY NOT? thanks

gnasher729
Feb 23, 2012, 05:29 PM
hi i need help again. i hit a road block.

i have a question that says "Write a single C++ statement that will print a random number from the set {4,9,14,19,24,29,34}

So i totally thought i could do this.

i figured it would be this:


for (int x = 4; x <=34; x+=5)
cout << (rand()%6+1) * 5 << endl;



and apparently thats not it but um WHY NOT? thanks

Let's do this step by step.

First, you need some random number. You call rand () for that. That's fine.

Next, you need a random number with seven different values. rand () % 6 won't do that, it will only give you six different values 0 to 5. So find an expression that will give you at random a value from 0 to 6.

Next find an expression that will give you at random one of the values 0, 5, 10, 15, 20, 25, 30.

Then find an expression that will give you at random one of the values 4, 9, 14, 19, 24, 29, 34.

Then print _one_ of these random values.

oxshannon
Feb 23, 2012, 05:32 PM
Let's do this step by step.

First, you need some random number. You call rand () for that. That's fine.

Next, you need a random number with seven different values. rand () % 6 won't do that, it will only give you six different values 0 to 5. So find an expression that will give you at random a value from 0 to 6.

Next find an expression that will give you at random one of the values 0, 5, 10, 15, 20, 25, 30.

Then find an expression that will give you at random one of the values 4, 9, 14, 19, 24, 29, 34.

Then print _one_ of these random values.

okay slightly confused on how to do the last three things you mentioned. im dumb. :confused:

thundersteele
Feb 23, 2012, 05:34 PM
hi i need help again. i hit a road block.

i have a question that says "Write a single C++ statement that will print a random number from the set {4,9,14,19,24,29,34}

So i totally thought i could do this.

i figured it would be this:


for (int x = 4; x <=34; x+=5)
cout << (rand()%6+1) * 5 << endl;



and apparently thats not it but um WHY NOT? thanks

What output do you get? I don't understand what you want to achieve with that for loop. But the random number should be written as:

(rand()%7 +1)*5 -1

rand()%5 gives you a random number from the set (0,1,2,3,4,5,6). With +1 and *5 you get a number from the set (5,10,15,20,25,30,35), and then you subtract 1.

I hope I didn't mess up :)

oxshannon
Feb 23, 2012, 05:36 PM
What output do you get? I don't understand what you want to achieve with that for loop. But the random number should be written as:

(rand()%7 +1)*5 -1

rand()%5 gives you a random number from the set (0,1,2,3,4,5,6). With +1 and *5 you get a number from the set (5,10,15,20,25,30,35), and then you subtract 1.

I hope I didn't mess up :)

Um i just thought that since it had to be from 4 to 34 in increments of 5 id need a for loop to show that. oops.

edit: when i try that, i just keep getting 4. should it be different each time i run it or what?

gnasher729
Feb 23, 2012, 05:59 PM
okay slightly confused on how to do the last three things you mentioned. im dumb. :confused:

Well, if you have one of the values 0, 1, 2, 3, 4, 5, or 6, then which operation would change this to one of the values 0, 5, 10, 15, 20, 25 or 30?

oxshannon
Feb 23, 2012, 06:11 PM
Well, if you have one of the values 0, 1, 2, 3, 4, 5, or 6, then which operation would change this to one of the values 0, 5, 10, 15, 20, 25 or 30?

so if i do rand%7+1 it would be a number ranged from 1 to 7, correct?
so *5 and then thatll be 5, 10, 15, 20, 25, 30, 35 and then i want 4, 9, 14, 19, 24, 49, 35 so i should just subtract one.

SO to answer my original question...


cout << (rand%7+1)*5-1 << endl; ? as was already posted, but want to make sure i understand the logistics behind it

thundersteele
Feb 23, 2012, 06:36 PM
(rand()%7)*5 + 4
would also work, and it's one operation less :)


Or:

int numbers[] = {4,9,14,19,24,29,34};

cout << numbers[rand%7] << endl;


edit: It would be more elegant to replace %7 with % length(numbers). But I don't know if this is easy to get in C.

oxshannon
Feb 23, 2012, 07:32 PM
(rand()%7)*5 + 4
would also work, and it's one operation less :)


Or:

int numbers[] = {4,9,14,19,24,29,34};

cout << numbers[rand%7] << endl;


edit: It would be more elegant to replace %7 with % length(numbers). But I don't know if this is easy to get in C.

this is a C++ class haha

thundersteele
Feb 24, 2012, 01:48 AM
this is a C++ class haha

Ah well, then you should implement a class that is instantiated with a list of numbers, and a method that returns one random element of that list when called.

Others might see this differently, but as long as you don't use object orientation (classes and inheritance), C and C++ are the same for me.

lloyddean
Feb 24, 2012, 11:31 AM
thundersteele,


...

"Write a single C++ statement that will print a random number from the set {4,9,14,19,24,29,34}

...

thundersteele
Feb 24, 2012, 11:40 AM
thundersteele,

Yes, it's also in the thread title... shame on me.

Now, how do you get the length of an array in C/C++? Is this even a sensible question to ask in C/C++, given that all arrays have to be initialized with a fixed length?

robvas
Feb 24, 2012, 11:51 AM
Yes, it's also in the thread title... shame on me.

Now, how do you get the length of an array in C/C++? Is this even a sensible question to ask in C/C++, given that all arrays have to be initialized with a fixed length?

int somearray[50];
sizeof(somearray*sizeof(int));

I think that works

Yup -

http://codepad.org/Zrx7ZrDR

lloyddean
Feb 24, 2012, 11:58 AM
Should be satisfied with, not counting the desire of calling 'srand':


std::cout << (((rand() % 7) * 5) + 4) << std::endl;


... as a statement ends with ';', or a compund statement with:


srand(time(NULL)), std::cout << (((rand() % 7) * 5) + 4) << std::endl;


... under an interpretation of the question.


Now, how do you get the length of an array in C/C++? Is this even a sensible question to ask in C/C++, given that all arrays have to be initialized with a fixed length?


Which question are you referring? Her Home work assignement or yours?


int arrray[] ={ 4, 9, 14, 19, 24, 29, 34 };

std::cout << "Length of 'array' is: " << (sizeof(array) / sizeof(array[0])) << std::endl;


The array can be added to at edit time by simply adding additional entries. No need to specify and modify a dimension value is required.

robvas version is problematic in that if the array type is changed it will require a corresponding change (a two for one) in the code. Greater chance of error than letting the compiler do the work.

thundersteele
Feb 24, 2012, 12:49 PM
Which question are you referring? Her Home work assignement or yours?


int arrray[] ={ 4, 9, 14, 19, 24, 29, 34 };

std::cout << "Length of 'array' is: " << (sizeof(array) / sizeof(array[0])) << std::endl;



My question. Sorry, I shouldn't mess around so much in this thread. Thanks for answering it!

chown33
Feb 24, 2012, 01:56 PM
int somearray[50];
sizeof(somearray*sizeof(int));

I think that works

Yup -

void main() {
char somearray[25];

printf("%d", sizeof(char) * sizeof(somearray));
}

Output:
25


Nope.

It works in that particular case, because sizeof(char) is 1. Try it with an array of ints and you'll see that expression doesn't work.

I'll leave it as an exercise to figure out the correct expression. Just remember this: sizeof() returns a value measured in bytes.

So it's just like any other unit of measurement where you have to convert from measurements into counts. E.g. if you have 10 meters of string, and it takes 14 inches to tie up a package, how many packages can you tie?

robvas
Feb 24, 2012, 02:23 PM
Nope.

It works in that particular case, because sizeof(char) is 1. Try it with an array of ints and you'll see that expression doesn't work.

I'll leave it as an exercise to figure out the correct expression. Just remember this: sizeof() returns a value measured in bytes.

So it's just like any other unit of measurement where you have to convert from measurements into counts. E.g. if you have 10 meters of string, and it takes 14 inches to tie up a package, how many packages can you tie?

My mistake, it should have just been sizeof(array)

For some reason I was thinking sizeof(array) would return the amount of elements and not the size in bytes. So you'd have to times that by the element's size.

http://codepad.org/23cGeSCA

lloyddean
Feb 24, 2012, 11:50 PM
My mistake, it should have just been sizeof(array)

For some reason I was thinking sizeof(array) would return the amount of elements and not the size in bytes. So you'd have to times that by the element's size.

http://codepad.org/23cGeSCA

I think you meant to say "So you'd have to divide that by the element's size."

oxshannon
Feb 28, 2012, 10:05 AM
Wirelessly posted (Mozilla/5.0 (iPhone; CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A405 Safari/7534.48.3)

I got an 89 on my my midterm! Made dumb mistakes :(

lloyddean
Feb 28, 2012, 12:15 PM
What dumb mistake did you make?

oxshannon
Feb 28, 2012, 03:02 PM
converting a for loop to a while loop
and then there was one "find correct the errors"
and i didnt see cout << Passed << and didnt put quotations on it haha. oops.

lloyddean
Feb 28, 2012, 07:35 PM
converting a for loop to a while loop

Would you mind elaborating?

mydogisbox
Feb 28, 2012, 07:40 PM
Would you mind elaborating?

Is that really necessary? Lets just leave it at: she did decently and she understands the material well.

lloyddean
Feb 28, 2012, 08:11 PM
I wish clarity, I'm not sure why you don't perhaps you should just stop reading!

oxshannon
Feb 29, 2012, 09:24 AM
the question gave a for loop and asked to convert it to a while loop and i messed up

balamw
Feb 29, 2012, 09:54 AM
I think lloyddean was asking in what way you messed that up. Did you get the exit condition wrong? The increment location? ...

B

oxshannon
Mar 1, 2012, 09:52 AM
Wirelessly posted (Mozilla/5.0 (iPhone; CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A405 Safari/7534.48.3)

I think lloyddean was asking in what way you messed that up. Did you get the exit condition wrong? The increment location? ...

B

We didn't get to keep our tests so I'm not sure I can exactly remember. I think I left out I= whatever it was supposed to equal. I only got like 2 points taken off so it wasn't a big deal

oxshannon
Mar 8, 2012, 08:23 PM
hi guys im back. your friendly neighbourhood amateur computer programmer.

i need help with this question.


2 Given the following array declarations:
(1) double a[30];
(2) int s(6) = {1, 2, 3, 4, 5, 6};
(3) int s[4] = {1, 2, 3, 4, 5};
(4) char[30] r;
(5) int s[] = {1, 2, 3, 4, 5};
(6) char str[] = “hello”;

Which of the following statements is correct?
(a) (2), (3) and (4) are wrong and the rest are correct.
(b) Only (1) and (6) are correct.
(c) Only (1) and (5) are correct.
(d) None of the above.


lol i know its probably not hard but arrays make no sense to me.. and i cant tell when soemthing is right/wrong



and


1 Which one is the correct function definition?
(a) void square(int &x)
{
int y ;
y = x*x;
cout << y << endl;
return y;
}

(b) square(int &x)
{
int y = x*x;
cout << y << endl;
return y;
}

(c) int square(int &x)
{
int y ;
y = x*x;
cout << y << endl;
}

(d)
void square (int &x)
{
int y = x*x;
cout << y << endl;
}

could someone tell me what exactly is wrong with the problems that are wrong? :D:D:D:D:D
i think the correct answer is d, because if its void you dont have a return, right?

robvas
Mar 8, 2012, 08:33 PM
If you need help with your homework, read your C++ book, or ask your teacher or a fellow student.

oxshannon
Mar 8, 2012, 09:06 PM
If you need help with your homework, read your C++ book, or ask your teacher or a fellow student.

i already explained my prof is extremely difficult to talk to and i dont know anyone in the class, thanks for the advice though mom

thundersteele
Mar 8, 2012, 09:10 PM
A few hints:

i) read about arrays in C++
ii) put the code in your program, hit compile. If the compiler throws an error, the code is probably wrong
iii) A function has to return the type that it was defined as, e.g. float has to return a float value, void shouldn't return anything


I'm surprised that all function examples pass the reference to the variable. Can someone explain why this would be good/bad?



http://www.cplusplus.com/doc/tutorial/arrays/

oxshannon
Mar 8, 2012, 09:14 PM
A few hints:

i) read about arrays in C++
ii) put the code in your program, hit compile. If the compiler throws an error, the code is probably wrong
iii) A function has to return the type that it was defined as, e.g. float has to return a float value, void shouldn't return anything


I'm surprised that all function examples pass the reference to the variable. Can someone explain why this would be good/bad?

my book just confused me more, sadly. im trying, i promise. its not that i want you guys to just tell me the answer or anything lol im just confused and want to know the rationale behind some things.


edit:: thanks for the link :)

oxshannon
Mar 8, 2012, 09:25 PM
i feel like 1, 3 and 5 in the first question i posted are correct, but theres no option for them. UGH this is so frustrating.

jk 3 is wrong isnt it?

thundersteele
Mar 8, 2012, 09:40 PM
i feel like 1, 3 and 5 in the first question i posted are correct, but theres no option for them. UGH this is so frustrating.

jk 3 is wrong isnt it?

The array is defined as having length 4, but is initialized with an array of length 5.

oxshannon
Mar 8, 2012, 09:42 PM
The array is defined as having length 4, but is initialized with an array of length 5.

it threw me off for a second because i know the index starts at 0, but i get it now.

so am i correct in saying that 1 and 5 are the only correct ones, would you agree? i really hope im right. lol

and the other questioni posted i THINK im right in saying the answer is d. so again, thanks for the helpppp

lloyddean
Mar 8, 2012, 09:48 PM
A few hints:
I'm surprised that all function examples pass the reference to the variable. Can someone explain why this would be good/bad?
http://www.cplusplus.com/doc/tutorial/arrays/

Explain, no. Perhaps they were writen by a mad man!

None of them modify 'x' and if that really is what was meant should probably be modified to:


<return-type> square(const int &x)


But would be better written as:


<return-type> square(int const x)

thundersteele
Mar 9, 2012, 02:54 AM
it threw me off for a second because i know the index starts at 0, but i get it now.

so am i correct in saying that 1 and 5 are the only correct ones, would you agree? i really hope im right. lol

and the other questioni posted i THINK im right in saying the answer is d. so again, thanks for the helpppp

Well, if you go back to that link I posted earlier, the chapter after arrays handles character sequences. That should help understand whether or not (6) is correct.

oxshannon
Mar 9, 2012, 07:43 AM
im confused whether its right or not, i dont think it is, but icant explain why very well. it just looks wrong in comparison to the examples on that site. for instance


char str[] = “hello”;


thats what im talking about btw.

gnasher729
Mar 9, 2012, 07:45 AM
2 Given the following array declarations:
(1) double a[30];
(2) int s(6) = {1, 2, 3, 4, 5, 6};
(3) int s[4] = {1, 2, 3, 4, 5};
(4) char[30] r;
(5) int s[] = {1, 2, 3, 4, 5};
(6) char str[] = “hello”;

Which of the following statements is correct?
(a) (2), (3) and (4) are wrong and the rest are correct.
(b) Only (1) and (6) are correct.
(c) Only (1) and (5) are correct.
(d) None of the above.

I hate multiple choice questions. Why not let the student mark each of 1 to 6 as correct or incorrect?

(1) is correct. Just an array of thirty doubles.
(2) is wrong. Uses the wrong brackets.
(3) is wrong. Too many initialisers.
(4) is just horrible. I don't care whether it is right or not, you should never write this. I think it's wrong. (That's the difference between language lawyer and developer. I don't care if its right, I wouldn't write it that way and I wouldn't let you write it that way).
(5) is correct. You get an array with five ints.
(6) is correct. A string literal can be used to initialise an array of char. If the array has no size then it gets an extra element for the trailing zero at the end of the string, so you get six chars. char str [5] = "hello"; would also be correct (no trailing zero), char str [4] = "hello"; would be wrong.

Practical tip: Let's say you have an array that should contain 57 constants. You wrote the code but you're not sure if you missed a constant or have one too many. So you declare the array with size 56, compile it and make sure that it fails. Then change the size to 57 compile it and make sure it doesn't fail.

oxshannon
Mar 9, 2012, 08:52 AM
I hate multiple choice questions. Why not let the student mark each of 1 to 6 as correct or incorrect?

(1) is correct. Just an array of thirty doubles.
(2) is wrong. Uses the wrong brackets.
(3) is wrong. Too many initialisers.
(4) is just horrible. I don't care whether it is right or not, you should never write this. I think it's wrong. (That's the difference between language lawyer and developer. I don't care if its right, I wouldn't write it that way and I wouldn't let you write it that way).
(5) is correct. You get an array with five ints.
(6) is correct. A string literal can be used to initialise an array of char. If the array has no size then it gets an extra element for the trailing zero at the end of the string, so you get six chars. char str [5] = "hello"; would also be correct (no trailing zero), char str [4] = "hello"; would be wrong.

Practical tip: Let's say you have an array that should contain 57 constants. You wrote the code but you're not sure if you missed a constant or have one too many. So you declare the array with size 56, compile it and make sure that it fails. Then change the size to 57 compile it and make sure it doesn't fail.

Those are the ones I thought were right, just dont like guessing blindly by going off other examples, i like to know why. Thanks a lot!!!

oxshannon
Mar 9, 2012, 10:34 AM
#include <iostream>
using namespace std;
#include <cstdlib>
#include <ctime>
#include <iomanip>
using std::setw;

int main()
{
const int arraySize = 10;
int freq [arraySize] = {0};

srand(time(0));
for (int i = 1; i <=100; i++)
++freq [rand()%10];

cout << "Number" << setw(13) << "Frequency" << endl;
for (int i = 1; i < arraySize; i++)
cout << setw(6) << i << setw(13) << freq[i] << endl;

return 0;
}


Here is what I'm trying to accomplish with this code:

Counting single digits) Write a program that generates one hundred random integers between 0 and 9 and displays the count for each number. Hint: use rand()%10 to generate a random number between 0 and 9. Use an array of ten integers, say frequency, to store the counts for the number of 0’s, 1’s, …, 9’s. Finally, output the frequency for each number.

My problem is I'm getting outputs where the frequency doesn't add up to 100, and also it doesn't display 0. I'm not sure what to do to fix this. Advice

EDIT: False alarm, I figured it out. I set i = 1 instead of 0 because I'm a dummmy.

balamw
Mar 9, 2012, 10:37 AM
Hint:

const int arraySize = 9;

How many digits between 0 and 9 inclusive?

EDIT: You were quick to edit the post. ;)

Next look at this line. What do you expect it to do?

for (int i = 1; i < arraySize; i++)

B

oxshannon
Mar 9, 2012, 11:08 AM
Hint:

const int arraySize = 9;

How many digits between 0 and 9 inclusive?

EDIT: You were quick to edit the post. ;)

Next look at this line. What do you expect it to do?



B

also realized i should have set i = 0. im being careless haha.

i have another problem i have to do where it acts me to input two real numbers , r and θ and return two numbers, x and y. according to x = r cos θ and y = r sin θ. i assume i need to use reference parameters. but i dont understand how to use θ in the program? can i use that as a variable in c++?

balamw
Mar 9, 2012, 11:24 AM
You can spell it out like theta or angle.

B

oxshannon
Mar 9, 2012, 11:38 AM
okay perfect, thanks :)

oxshannon
Mar 9, 2012, 02:53 PM
lol k so i did this code up


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

double polar (double &, double &);

int main ()
{
double r, angle;

cout << "Enter two numbers for polar coordinates: " << endl;
cin >> r, angle;
polar (r, angle);
cout << "The corresponding rectangular coordinates are (" << x << ", " << y << ")"

return 0;
}

double polar (double & r, double & angle)
{
double x, y;

x = r* cos (angle);
y = r * sin (angle);

return x, y;
}


To satisfy this question:


11 Define a function that can convert the polar coordinates into rectangular coordinates, that is input two real numbers, r and θ, and return two numbers, x and y, according to the following formula:
y = r sin theta, x = r cos theta
You must use reference parameters to return two values. Then write a program that will prompt user to input two numbers, call the function and output the results. The sample output is
Enter two numbers for polar coordinates: 3.5 20
The corresponding rectangular coordinates are (3.19531, 1.42829)


my question is.. what exactly did i do wrong? i am still pretty rough on user defined functions.. and i thought i was doing so well!!! but it doesnt work.. says use of undeclared indentifier x and y. disappointing.

balamw
Mar 9, 2012, 03:10 PM
Hint. Pass by value those things you don't want/need to change in the function and pass by reference those things you do want/need to change. How many variables altogether do you need to pass to your function? What data type does it need to return?

B

oxshannon
Mar 9, 2012, 03:22 PM
Hint. Pass by value those things you don't want/need to change in the function and pass by reference those things you do want/need to change. How many variables altogether do you need to pass to your function? What data type does it need to return?

B

im pretty sure it needs to return double, right? and altogether i need to pass 2 values?? im confused so im not sure..

balamw
Mar 9, 2012, 03:24 PM
Break the problem down.

You need to pass r and angle. Do you need to change their values? You also need to return x and y, both doubles. How might you do that if the function can only return a single value?

B

lloyddean
Mar 9, 2012, 03:55 PM
Shannon,

Have you covered the C/C++ keyword 'struct' in class yet?

balamw
Mar 9, 2012, 04:01 PM
Shannon,

Have you covered the C/C++ keyword 'struct' in class yet?

The problem statement says:

You must use reference parameters to return two values.

So I would guess no.

B

lloyddean
Mar 9, 2012, 04:05 PM
Didn't see that first read through!

oxshannon
Mar 9, 2012, 04:15 PM
Break the problem down.

You need to pass r and angle. Do you need to change their values? You also need to return x and y, both doubles. How might you do that if the function can only return a single value?

B

r and angle are going to have to have their values changed right? why can the function only return a single value? and on top of that, HOW might i do that? lol ugh

----------

The problem statement says:



So I would guess no.

B

correct :-)

----------

so am i at least on the right track here? i feel useless haha

lloyddean
Mar 9, 2012, 04:20 PM
and return two numbers, x and y, according to the following formula: y = r sin theta, x = r cos theta

Does anything in the formula imply the need to change either 'r' or 'theta'?

oxshannon
Mar 9, 2012, 04:22 PM
Does anything in the formula imply the need to change either 'r' or 'theta'?

mmm no i guess not? i dont really understand reference parameters but im tryyyying

macuser1232
Mar 9, 2012, 04:26 PM
So have we found out a program that allows a Mac to run C++, because when I get into coding I want to know if I will have to buy a PC or not. I love Macs and I hope Apple starts making them more compatible with things.

lloyddean
Mar 9, 2012, 04:29 PM
mmm no i guess not? i dont really understand reference parameters but im tryyyying

Were you given any examples of using pass by reference?

oxshannon
Mar 9, 2012, 04:30 PM
So have we found out a program that allows a Mac to run C++, because when I get into coding I want to know if I will have to buy a PC or not. I love Macs and I hope Apple starts making them more compatible with things.

This is what I used: https://github.com/kennethreitz/osx-gcc-installer
Or you can download xcode, you definitely won't need to buy a PC.

----------

Were you given any examples of using pass by reference?

no not really just a comparison between pass by reference and pass by value that makes minimum sense. i dont get anything out of lecture, i learn everything in lab because my lab instructor knows what she is talking about, but sadly this assignment is due before the correspondng lab.

macuser1232
Mar 9, 2012, 04:31 PM
This is what I used: https://github.com/kennethreitz/osx-gcc-installer
Or you can download xcode, you definitely won't need to buy a PC.

----------



no not really just a comparison between pass by reference and pass by value that makes minimum sense. i dont get anything out of lecture, i learn everything in lab because my lab instructor knows what she is talking about, but sadly this assignment is due before the correspondng lab.
Thanks ill download that. and yeah I already have Xcode and I have only used it about 2 times.

balamw
Mar 9, 2012, 04:32 PM
Thanks ill download that. and yeah I already have Xcode and I have only used it about 2 times.

If you have Xcode you already have gcc/clang and can compile C++. No need to download install anything else.

B

lloyddean
Mar 9, 2012, 04:33 PM
void give_me_a_number(int & number)
{
number = 5;
}


... somewhere in deep cyberspace someone writes ...


int number_given;
give_me_a_number(number_given);

std::cout << "I was given the number: " << number_given << "\n";

macuser1232
Mar 9, 2012, 04:36 PM
does anyone know if they make an ffviewer for mac yet??

----------

If you have Xcode you already have gcc/clang and can compile C++. No need to download install anything else.

Boops and ok good. i wasn't sure if Xcode could code C++

----------

Xcode vs GCC? which one is better?

oxshannon
Mar 9, 2012, 04:37 PM
:( i feel so lost and discouraged now i thought things were going so well. its so frustrating not to be able to do something

macuser1232
Mar 9, 2012, 04:38 PM
:( i feel so lost and discouraged now i thought things were going so well. its so frustrating not to be able to do something
what are you not able to do?

oxshannon
Mar 9, 2012, 04:40 PM
what are you not able to do?

the program i posted earlier (a few posts up) i thought it would work for the question i needed to do and i dont understand why it doesnt. #newbieproblems

lloyddean
Mar 9, 2012, 04:40 PM
Just gave you an example use of pass by reference and how to call it.

Test it out see what happens!

balamw
Mar 9, 2012, 04:40 PM
Xcode vs GCC? which one is better?

Xcode is an IDE, gcc is a collection of compilers (gcc = GNU compiler collection) that is used by some versions of Xcode. The newest versions of Xcode are migrating to clang instead of gcc.

B

macuser1232
Mar 9, 2012, 04:41 PM
Xcode is an IDE, gcc is a collection of compilers (gcc = GNU compiler collection) that is used by some versions of Xcode. The newest versions of Xcode are migrating to clang instead of gcc.

Bim going to stick with Xcode. by the way, does anyone use Coda here?

balamw
Mar 9, 2012, 04:41 PM
what are you not able to do?

Note, this is a homework problem so lad the OP don't solve it for them.

B

oxshannon
Mar 9, 2012, 04:44 PM
Just gave you an example use of pass by reference and how to call it.

Test it out see what happens!

I saw that, thats what is confusing me. Lol i am hopeless i think.

----------

should i just scrap everything i have done and start over? or is there some hope for what i did already? i really dont even know WHERE Its wrong. ugh

lloyddean
Mar 9, 2012, 04:48 PM
No! You're pretty close.

Try this example!


#include <iostream>

void give_me_a_number(int & number)
{
number = 5;
}

int main()
{
int receiving_variable = 15000;
give_me_a_number(receiving_variable);

std::cout << "We received the number: "
<< receiving_variable
<< "\n";
}

balamw
Mar 9, 2012, 04:49 PM
should i just scrap everything i have done and start over? or is there some hope for what i did already? i really dont even know WHERE Its wrong. ugh

The "meat" of your posted code seems fine, but it's your interfaces that need work. (Which is the point of the exercise).

B

oxshannon
Mar 9, 2012, 04:55 PM
@lloyddean: I ran that and understand it, but its when things get difficult i get confused.

im so frustrated :(!! and i dont want you guys to feel pity for me and give me the answer btw, because i want to feel accomplished when i finally figure it out but i feel like im at a dead end hahaha

balamw
Mar 9, 2012, 04:56 PM
How might you extend lloyddean's code to return two separate numbers?

B

oxshannon
Mar 9, 2012, 04:56 PM
How might you extend lloyddean's code to return two separate numbers?

B

i have absolutely no idea.

lloyddean
Mar 9, 2012, 04:58 PM
You might think of references as a way of sharing non global local variable with subroutine.

oxshannon
Mar 9, 2012, 05:00 PM
You might think of references a non global way to share a local variable with subroutine.

:confused:
confusing. we spent about 20 seconds on global variables and local variables.
i wish my professor wasnt so terrrrible. im really trying here guys i promise

lloyddean
Mar 9, 2012, 05:04 PM
local variables to a function are not available to any code outside the function. Yet something magical just happened! What was it?

EDIT: Slight corrections to syntax and spelling.

oxshannon
Mar 9, 2012, 05:06 PM
local variable to a function are not available to any code outside the function. Yet something magical just happened! What was it?

im not sure of what this magical-ness is you speak of because im lost LOL.

lloyddean
Mar 9, 2012, 05:08 PM
What was the result of running the example code?

balamw
Mar 9, 2012, 05:10 PM
Specifically, the value of receiving_variable before and after
give_me_a_number(receiving_variable);

B

oxshannon
Mar 9, 2012, 05:22 PM
What was the result of running the example code?

the number that was outputted was outside of the main function?

----------

the more im trying to fix this the more errors im getting :(

----------

am i getting closer or farther away ?


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

double polar (double &, double &, double, double);

int main ()
{
double & x, & y, r, angle;

cout << "Enter two numbers for polar coordinates: " << endl;
cin >> r, angle;

polar (x, y, r, angle);

cout << "The corresponding rectangular coordinates are (" << x << ", " << y << ")" << endl;

return 0;
}

double polar (double & x, double & y, double r, double angle)
{

x = r * cos(angle);
y = r * sin(angle);

return x, y;
}

lloyddean
Mar 9, 2012, 05:25 PM
So, what was it about the definition (or interface) of 'give_me_a_number' that allowed a LOCAL variable in main to be modified?

oxshannon
Mar 9, 2012, 05:27 PM
So, what was it about the definition (or interface) of 'give_me_a_number' that allowed a LOCAL variable in main to be modified?

the (int & number)?

balamw
Mar 9, 2012, 05:31 PM
Closer.

Take a look at lloyddean's code. What data type and value does give_me_a_number return and why?

B

lloyddean
Mar 9, 2012, 05:37 PM
Oh, and you're getting warmer! Look closer a my example. What differences do you see?

----------

the (int & number)?

Correct! The '&' gives 'number' direct access to whatever variable it was passed.

oxshannon
Mar 9, 2012, 05:43 PM
it returns an integer? because its an integer data type??

----------

on a side note, the errors i get when i run this code confuse me.


polar.cpp:9:11: error: declaration of reference variable 'x' requires an
initializer
double & x, & y, r, angle;
^
polar.cpp:9:16: error: declaration of reference variable 'y' requires an
initializer
double & x, & y, r, angle;
^
polar.cpp:12:12: warning: expression result unused [-Wunused-value]
cin >> r, angle;
^~~~~
polar.cpp:27:9: warning: expression result unused [-Wunused-value]
return x, y;
^

.... Why do x and y have to be initialized, and what are those warnings saying? is this related to what you guys are talking about or no?

lloyddean
Mar 9, 2012, 05:48 PM
Take a look at <http://www.parashift.com/c++-faq-lite/references.html>

oxshannon
Mar 9, 2012, 05:48 PM
oh and also when do you use void? i know if you use void you dont have a return thing, but how do you know when to do it?

so what should they be initialized to..? -_-

lloyddean
Mar 9, 2012, 05:55 PM
Good question.

The problem with giving an answer is that not having been through your class I don't know what you've covered in class to date and thus don't have a shared context with which to craft a useful answer.

oxshannon
Mar 9, 2012, 05:56 PM
even if we did cover it in class, i probably didnt understand. this professor is a joke

lloyddean
Mar 9, 2012, 06:02 PM
I think we're out of sync. Where are we at with your understanding of and answering your homework?

oxshannon
Mar 9, 2012, 06:05 PM
um still not that great. i dont understandwhat i should initialize x and y to. i looked in my book and the only example on the reference stuff is with the quadratic equation and i cant follow it what so ever. so its not looking too great. im really not sure what else im supposed to change here! i feel like im close though

edit:
so i changed the main body of my code


int main ()
{
double x;
double y;
double r;
double angle;


because in the example i have it doesnt show the & in the initialization. when i do this the program runs, but its still wrong. ie: if i input 3, it spits 3 back out. so i know im not done, but was this a good move? is the & not supposed to be in the main body?