View Full Version : [C++] Tutorial 1: Discussion
dduardo
Jun26-04, 09:25 AM
Please post your C++ questions or comments here for Tutorial 1.
Please post your C++ questions or comments here for Tutorial 1.
Man!
What do you mean by tutoriel ? hmm ?
dduardo
Jun26-04, 10:17 AM
Look at the sticky below this thread. I'm in the process of writing up the first part. I will post it very soon.
Sorry I didn't read your notice post right above before giving a comment,
OK, seriously, the topics you listed gave me an impression of my first days in college, biting my nails and my pencil from time to time listening to my Delphi teachers trying to explain what was necessary to become a programmer, because I was starting to learn programming languages with Delphi and Basic, although their syntax and structures have been utterly erased from my memmory. What a Cool tutor you are, I have to say that!
Before introducing about array, or perhaps while you are writing about it, i also think if pointer is important enough to be included, to be digged as deeply as possible.
I think conditional statements and iterative or control statements should also dig dig diged deeply too, especially should give students some ideas of how to use if/else effectively as possible since I believe these things will be mentioned more in their future (thisz juts my personal idea). Those who hav some basic skills in progremming will suun grasp the control statements, but handling problems with those are again letthem go back to how to correctly use iterators and operators.
Ok, frankly I'm sleepy now, I can only give some *rough* draft/ideas or acutlay nothing, hoep some piple will join in to make htis much interesting and more *beautiful*.
Finaly, Stick with the Standard and update infor all the time, yor tutoriels'll look as handsome as Mangan does! :D
+Nec
*I guess :shy: there're some thinkings taht I am Mangan :shy:, byt it only happens after i see my doctor and ask her to change my all :shy:*
(tomorrow or acouple of days later, I will try to write more about what i think)
Sorry for short and quite menaingless comments-if they turn out to be so.
dduardo
Jun26-04, 11:00 AM
Nec, yes, I will give plenty of real world examples. What I'll do is revise and add more content to my previous postings for those who are still have difficulty while still creating new tutorials so people who already have basic programming skills don't feel like the course is going slow.
exequor
Jun27-04, 11:32 PM
hey dduardo this is a really cool idea. i enjoyed it from since the java classs was implemented and seeing c++ i was amazed because 1. i recently started the language and 2. i use dev c++ and thats a featured program in your tutorial so I just like to let you know that what you are doing is really appreciated. its like going to school on the web.
Monique
Jun30-04, 03:33 PM
Very good dduardo!! :smile: :smile:
A good resource I can learn something from :approve:
Hey, first I was want to say good job, It's nice to see somebody who's willing to input the effort and time to help others.
Anyways...
If I had to suggest something... I would ask you to clarify your code examples a little.
like this excerpt...
int x = 1, y = 3, z = 4;
int *num;
const float pi = 3.14;
z*=y;
y = x + (int)pi;
num = &y;
if you could go into a tad more detail I'm sure that I and others would appreciate it. I know that playing around with it is a good way to learn, but I'm having a hard time understanding what's going on there and I just think it would help if you gave a little push.
Other than that though, great tutorial and I'm looking forward to the next parts.
Hey this is great. I'm just about to take a c++ class this summer. Great timing dduardo
hey i got a question..
suppose class Foo has function returnMe. it has no variables (meaning returnMe() without any arguments)
Foo x;
x.returnMe();
this should return an OBJECT x. So basically it just returns itself.
How do i define Foo :: returnMe() { } ??
00XeRo, will do. I have been a little busy with my own software project, so updating has been a little slow.
*****Advanced C++ Below. It has nothing to do with the tutorial*****
cronxeh if you want a class to return itself use the this pointer. The this pointer is a c++ keyword. Here is an example of how it works:
#include <iostream>
using namespace std;
class foo {
public:
foo* returnme(void);
};
foo* foo::returnme(void) {
return this;
}
int main( int argc, char *argv[] ) {
foo x;
foo *y;
y = x.returnme();
cout << y << endl;
cout << &x << endl;
return 0;
}
If you run this program you will see that y points to the base address of x. Therefore y is x.
I always wonderd what the arguments were that are inside the main meathod
int main( int argc , char **argv )
what are int argc, char **argv?
The arguments inside of main are used to store command line arguments. For instances:
ping -A localhost
"ping" is the program name and "-A localhost" are the arguments. The environment your in will pass the argument part to your program. Argc or Argument Count will tell you that there are 2 arguments - "-A" and "localhost". Argv or Argument Value is an array of pointers (or a pointer to a pointer) that stores the actual agrument strings.
int main( int argc, char **argv) is equivalent to int main( int argc, char *argv[] )
[edit] gnome, your right, it is an array of pointers. I should make a point about that subtle distinction in my tutorial.
An array of pointers:
int *array[];
A pointer to an array
int (*array)[];
/*They are there to allow you to pass parameters into the program from the command line.
argv[] is an array of pointers to your parameters; the parameters are stored as character strings.
argc is the number of parameters.
argv[0] always points to the name of the program, so argc is always >= 1
For example, here is a program that prints "hello" followed by whatever string the user types after the program name at the command line, or just "hello." if no parameters are supplied:
*/
#include<iostream>
using namespace std;
int main(int argc, char *argv[]){
cout << "hello";
if (argc>1)
cout << ",";
for (int i=1; i < argc; i++)
cout << " " << argv[i];
cout << "." << endl;
return 0;
}
DarkAnt
Jul13-04, 12:45 PM
ok, apparently I was supposed to know C before taking this class. My teacher wants me to use a header file. What exactly do I put in a header file and could you show me an example?
dduardo
Jul17-04, 11:01 PM
When you want to include a header in a file you should write something like this:
#include "myheader.h"
The header file should contain something like this:
#ifndef MYHEADER_H
#define MYHEADER_H
//CODE
#endif
DarkAnt
Jul18-04, 05:36 PM
what type of code would I put in there?
sorry I'm so dense
In C++ typically you would put a class definition in a header file (.h) -- just the declaration of the class, containing a bunch of one-line declarations of all of the methods and data members of the class.
Then, the code to implement all of the methods goes in an implementation file (.cpp).
dduardo
Jul18-04, 06:41 PM
DarkAnt, the code you put there are your functions.
exequor
Jul20-04, 10:14 AM
hey dduardo when you are finished with the main topics are you going to give a tutorial on using some gui toolkit or so?
dduardo
Jul20-04, 10:36 AM
Which gui toolkit do you want? FLTK, GTK, QT?
exequor
Jul27-04, 10:13 AM
i have wxwindows and fltk added to dev cpp but i just can't seem to find a download for GTK with dev cpp. Its not like i want to learn them all I was just experimenting to see which one i should go with so that later on i don't regret choosing one then having to make a switch. It would be nice to know which one you think is best? Do u do any gui by the way?
DarkAnt, the code you put there are your functions.
Would that be something to enable your mathematical functions such as square root, etc.?
Not that making your own isn't fun. Check this out - a mathematical transmission. Newton-Raphson doesn't work so well at extremely low or extremely high "rpms". Pushing the significant digits into Newton-Raphson's most effective range and tracking the powers of ten separately makes this run a lot better, especially for those problem numbers like "What's the square root of 1.01?" which converge somewhere between here and eternity.
Using recipricals for numbers less than one makes things a lot easier to deal with, as well (like that annoying divide by zero problem when you try to find the square root of .5)
Being able to find the square root on three sticks of bamboo slapped together 50 years ago easier than my program could got so frustrating I decided to just give in and borrow a couple slide rule tricks. :approve:
//Name: Bob
//Filename: squareroot.cpp
#include<iostream.h>
void main()
{
//variables
double my_number=-1, temp_number, difference_number;
int count,recip=0,napier=0;
const int max_count=25;
const double tolerance=.000001;
//input (no negatives allowed)
while(my_number<0)
{
cout <<"Input number: ";
cin >>my_number;
if(my_number<0)
{
cout <<"You must enter a positive number!" <<endl;
}
else
{
}
}
cout <<endl;
//pre-processing (if number less than one, use reciprical)
if(my_number<1)
{
recip=1;
my_number=1/my_number;
}
else
{
}
//pre-processing (Napier's method to speed processing)
if(my_number<10)
{
my_number=my_number *100;
napier=-1;
}
else
{
while(my_number>1000)
{
my_number=my_number/100;
napier++;
}
}
//processing (Newton-Raphson method)
count=0;
temp_number=my_number;
while(count<max_count)
{
difference_number=my_number-temp_number*temp_number;
if(difference_number<tolerance && difference_number * (-1) < tolerance)
{
break;
}
else
{
temp_number=temp_number-difference_number/(1-2*temp_number);
}
count++;
}
//post-processing (undo Napier's)
if(napier==-1)
{
temp_number=temp_number/10;
my_number=my_number/100;
}
else
{
while(napier>0)
{
my_number=my_number*100;
temp_number=temp_number*10;
napier--;
}
}
//post-processing (if reciprical was used, flip back to original)
if(recip==1)
{
temp_number=1/temp_number;
my_number=1/my_number;
}
else
{
}
//output
if(difference_number<tolerance && difference_number * (-1)<tolerance)
{
cout << endl << "Square root of " <<my_number <<" is: " <<temp_number <<endl;
}
else
{
cout << endl << "Routine failed to converge! " <<temp_number << endl;
}
return;
}
Sorry Bob, I didn't mean to be that impolite anyway, :wink: :biggrin:, Hello !
I dis- :approve:
Your coding style I have to say is really really :biggrin:
Can you please change the dot h into no-dot-h ?
The Standard tells me that I have to return an int in main-function instead of void.
I think so,...-lol-
Over!
hey dduardo when you are finished with the main topics are you going to give a tutorial on using some gui toolkit or so?
If you could give all members tutorials in biology ? :biggrin:
I don't know why no one thinks up some tutorials in LISP ? I am learning, it is used a lot in PR, NN.
It is so kind of you to give people this tutorial anyway.
Thank DDuardo :biggrin:
Sorry Bob, I didn't mean to be that impolite anyway, :wink: :biggrin:, Hello !
That's okay. I know a little Basic, but C++ is completely new to me.
I already know the iostream can go either way (evidently, different compilers handle it differently and our teacher warned us that we might have to drop the .h if we used this at home on a different compiler).
Totally clueless on the main function (we've only had two classes, so far).
At least starting to get a feel for having to live without any line numbers.
jwyw0813
Sep14-04, 01:54 AM
hello everyone,
i would like to have a function to Minimize the average waiting time of N print jobs using c++.
i am thinking of using heap class to build it
i have read a book and it has the follow idea.
the first line is the number of job needed to be do
subsequent lines - arrival time, length of job
sample input 1
6
0 7
0 2
0 1
5 10
6 3
8 5
Average waiting time : 4.33
However i dont know how to calculate the waiting time out and how to start
can anyone teach me how to do that , thx all :smile:
jwyw0813, a greedy algorithm should work. If you are not familiar with "greedy": search "\"job schedule\" greedy" on google.
A quick idea is: add jobs to the heap in non-descending order of their starting time and use as ordering criteria for the heap their end times. I have omitted some details and, more important, I haven't proved this works -- and neither tried it, so be sure to take the info in this paragraph with a grain of salt.
As for the heap.. If you are writing the program in C++ then you might be better of using std::set instead of a heap (because it is readily available from the standard library). In Java you have TreeSet. In C# you have SortedList (this might be slower...),. In OCaml you have Set, etc. In short you can use a set-like DS, which is usually implemented as a balanced search tree, instead of the heap, simply because heap implementations are not readily available in most standard libraries.
SahinTC
Sep30-04, 01:50 AM
I've been programming in C++ for around four to five years right now, and have to say I wish I had a tutorial like that when I started.
You might really want to teach Hungarian notation and standard naming conventions though.
Err, you know:
methods: methodNameHere()
constant: CONSTANT_HERE,
integer: iNum1, iNum2,
float: fNum1, fNum2
I say this because it really helps make the code neat and simple to read and understand.
Also, for anyone else interested, I would highly recommend the Deitel and Deitel book, C++ How to Program. Hands down one of the best books for beginners.
EDIT: Might also want to include a blurb on Dev C++ (http://bloodshed.net), in my opinion the best free IDE for C++ there is. IDEs generally make the process of learning how to code from scratch much easier than working with commandline executed compilers. Plus, syntax hilighting is nice. :)
Hungarian notation is an historical one. Everybody agrees these days that it is obsolate (see Java or .NET coding standards for example.
As for the book, just look at:
http://www.accu.org/cgi-bin/accu/rvout.cgi?from=0au_d&file=cp003204a
The conclusion: "Do not buy this book, and if someone tries to give you a copy decline, politely, then firmly."
If you want good books look for:
Bjarne Stroustrup, The C++ Language (the "c++ bible" by the creator of the language)
Effective C++ & More Effective C++, Scott Meyers (nice idioms)
Design Patterns, Gamma et. al (designing big applications)
Modern C++ Design, Andrei Alexandrescu (advanced _language_ usage, very heavy on templates)
In general, when you consider buying a book make a visit to www.accu.org to see at least one authorized opinion.
hatefilledmind
Nov25-04, 06:07 AM
I was never a fan of Hungarian notation. However if you have to edit source code for a Win32 program you might come across it, so you should at least be aware of what it is.
I've never read the Deitel & Deitel book on C++ (I have their book on Java, it's OK), but to imply that a book for beginners is in the same class as an exhaustive C++ reference book (the one by Stroustrup) and an advanced text on OO design for software professionals and other advanced users is unreasonable. Those are good books but not suitable for those without substantial experience (either with C++ or OOP in general). And there's a lot to learn in C++.
ramollari
Dec1-04, 03:53 AM
Those are good books but not suitable for those without substantial experience (either with C++ or OOP in general). And there's a lot to learn in C++.
I've read C++ How to Program from Deitel & Deitel, and it is excellent for beginners. It's not just learning C++ but learning programming concepts from the beginning in most structured way. The treatment of structured programming especially is great. I think it is useful for professionals as well who need to consolidate the messy knowledge they have in mind, and to write clearer programs.
I just would like to read a book for MFC with C++ but I'm not finding an appropriate one.
ramollari
Dec1-04, 05:05 AM
Design Patterns, Gamma et. al (designing big applications)
This is a classically important book of course, but if you ever read that book you'd understand that it is not for learning C++. How could a beginner understand what are patterns whithout knowing about design, or worse about programming basics.
"Design patterns" is, as I said, for designing applications -- in any OO language.
For structured programming you are better of with Dijkstra's "Structured programming" book. His writing style is excelent.
Why exactly do you want to learn about MFC? It is old and a very good example of BAD library design. You would be much better off learning .NET class library or Java API.
ramollari
Dec8-04, 03:08 AM
Well, MFC are the libraries that I have in my compiler, Microsoft Visual C++ 6.0. But I'd be willing to learn any other libraries for GUI in C++.
Then have a look at:
http://lab.msdn.microsoft.com/express/ and
http://java.sun.com/
Both come with pretty comprehensive documentation (both tutorials and reference material).
I recommend the
Algorithms in C++ series by Robert Sedgewick
Code Complete (2nd Edition)
Code: The Hidden Language of Computer Hardware and Software - the book is on computer foundations and architecture, fair introduction to computer science
Ryan
LogiX: your recommandations are better than mine!
From the same area: The Pragmatic Programmer, a book full of practical advices presented thru analogies that helps you remember.
One example: The Broken Window Theory. The advice: Never leave something broken (if you know it is broken). Story: A study of NY police with sociology&psychology researchers was intended to shed some light on when property is destroyed. They left an expensive car in an ill-famed neighborhood. A few weeks nothing happened. Then they broke a window. Within a few hours the car was completely destroyed and set on fire. Conclusion: Never leave something broken.
exequor
Jan11-05, 05:25 PM
Well, MFC are the libraries that I have in my compiler, Microsoft Visual C++ 6.0. But I'd be willing to learn any other libraries for GUI in C++.
If you want to do GUI work outside of ms visual c++, I recommend using devcpp along with gtk and glade. Glade is just like the form builder you have in visual basic and it builds the code for you c/c++ project making use of GTK. The good thing is everything is free.
If you want to do GUI work outside of ms visual c++, I recommend using devcpp along with gtk and glade. Glade is just like the form builder you have in visual basic and it builds the code for you c/c++ project making use of GTK. The good thing is everything is free.
As well as cross-platform.
exequor
Jan11-05, 10:45 PM
As well as cross-platform
The only thing that is not cross-platform is devcpp, which is only for windows.
visual basic is cross platform?
exequor
Jan23-05, 08:22 AM
visual basic is cross platform?
I thought that cross-platform meant that something could work on multiple OSs or be compiled for multiple OSs. I didn't know that VB could do that.
It's important to understand that Dev-C++ is not a compiler. Dev-C++ is an IDE (Intregrated Development Environment) that uses the MingW (windows port of GNU GCC) compiler.
I personally recommend using wxWidgets as a GUI API. It's build in a very OO manner which makes it easy to learn and work with. And, it is extremely portable across multiple platforms. http://www.wxwidgets.com
Visual Basic executables are not cross-platform.
Ryan
I thought that cross-platform meant that something could work on multiple OSs or be compiled for multiple OSs. I didn't know that VB could do that.
What I meant was that you can write programs for many different platforms with c++, while Visual Basic limits you to Windows.
Just use Delphi, it gets ride of this annoying ActiveX files. If you are making a windows app, use VB, if you need speed, use Delpi or CPP, if you need platform control, use Java, c#, C++, ect...
I recomend for anyone who is new to programing to start off with Visual Basic, then move on to something else.
ramollari
Feb11-05, 07:53 AM
I recomend for anyone who is new to programing to start off with Visual Basic, then move on to something else.
Let me say that Visual Basic is not the proper language to start with. It is too visual, too buggy, too inefficient, and too difficult to understand.
Not to mention that it's not free!
I thought QBASIC was a beautiful language, is VB really that bad? (Of course, I had not yet heard of Pascal or C++ at that time in my life)
ramollari
Feb11-05, 08:09 AM
Not to mention that it's not free!
I thought QBASIC was a beautiful language, is VB really that bad? (Of course, I had not yet heard of Pascal or C++ at that time in my life)
It is all commercial: the language and the development environment. That is to the advantage of Microsoft.
Also by the way VB is little related with QBASIC. When I think of VB I think of 'drag and drop', not of programming.
VB is useful for prototyping and for RAD software development. But not for beginners who want to learn programming principles. C++ would be a good one.
Davorak
Feb11-05, 07:00 PM
I started out with VB, and I agree. After I started programing in C++ I felt like I wasted alot of time of VB. Oh well live and learn.
VB is useful for prototyping and for RAD software development. But not for beginners who want to learn programming principles. C++ would be a good one.
Python would be an even better one. Simple syntax, while teaching modern programming principles. Even after you move on to a different language, it's still great for scripting!
SqrachMasda
Feb28-05, 07:31 PM
my question is simple, i think, but it still killing me in class
i kinda gave up on learning new stuff, because i still have not been able to successfully run it,....nothing to do with errors(though i'll have those) but i dont know the specific way to run a program when u finish,...the ending part just does not make sense for me, pretty much because i dont know how to do it
my question is simple, i think, but it still killing me in class
i kinda gave up on learning new stuff, because i still have not been able to successfully run it,....nothing to do with errors(though i'll have those) but i dont know the specific way to run a program when u finish,...the ending part just does not make sense for me, pretty much because i dont know how to do it
You're gonna have to be a bit more specific, mate :frown:. What language are you using? What compiler? Can you post exactly the problem you're having and post the source of what you have so far?
Adam Y.
Mar25-05, 10:35 PM
Not to mention that it's not free!
I thought QBASIC was a beautiful language, is VB really that bad? (Of course, I had not yet heard of Pascal or C++ at that time in my life)
Oddly enough that's not entirely true. .net express (http://lab.msdn.microsoft.com/express/)
gsolvers
Jun7-05, 02:15 AM
i am creating two fileds a header file function.h with function wel() defined in it and a main file main.c which is calling wel() function define inside function.h. Hope this is enough.
function.h
public void wel()
{
printf("Hello Welcome !");
}
main.c
# "header.h"
int main(int argc, char *argv[])
{
wel();
return 0;
}
neurocomp2003
Jun7-05, 01:28 PM
people shouhld alwasy start with pascal =]
Please post your C++ questions or comments here for Tutorial 1.
I am having trouble getting my multidimensional array to do what I want it to do. Here is an exmple
of how I want this to look and how it will work.
row 1) Part Description | Part number //this is multidemsional array PD( row 1,columns 1-18 ), m array P#
row 2) Cam | 2110 // PD [1][0-4],Cam[1][0-4]
row 3) air filter | 1111 // PD [2][0-10],cam[2][0-4]
ect
My goal is on the first time the order function is entered to have row 1 and 2 display, the 2nd time the order function is entered rows 1,2,3 will display, the third rows 1,2,3,4 ect. Also the array will only display addresses not what it is supposed to. I know this is not an easy thing to do but I am not able to think of any other way to show all of the ordered items. Helllllllllllp plllllllllllllllease...........
here is the code I have.
#include <iostream>
#include <iomanip>
#include <ctype.h>
#include <stdlib.h>
using namespace std;
void partsorder(char order[]);
void list(char order[]);
int zz = 0;
const int ROWS = 50;
const int COLS = 50;
const int CAM = 20;
int main()
{
char shaft[CAM]="";
do
{
cout << "The cam number is 2110. The cam kit number is 2110k. Please enter\n"
<< "the approiate part number ";
cin.getline(shaft,CAM);
if (shaft[0] != 0) //if shaft is not null then goto
list(shaft);
}while(shaft[0] != 0);
}
void list(char order[])
{
if (zz == 0){
cout << " | Part Description |" << " Part # |\n ";
partsorder(order);
}
else {
partsorder(order);
}
}
void partsorder(char order[])
{
int num = 0, e = strlen(order);
num = atoi(order);
char c[CAM] = "Cam";
char ck[CAM] = "Cam kit";
char b,pd[ROWS][COLS];
zz++;
switch (num)
{
case 2110:
if (e == 4){
for(int y = 0; y < COLS; y++){
pd[zz][y]=c[y];
}
//strcpy(pd,c);
b = ' ';
//cout << "Please enter the quantity -->";
//cin >> q;
//price = 86 * q;
break;
}
else if (e == 5) {
for(int y = 0; y < COLS; y++){
pd[zz][y]=c[y];
}
//strcpy(pd,ck);
b = 'k';
//cout << "Please enter the quantity -->";
//cin >> q;
//price = 136 * q;
}
}
int x = 0;
for(int y = 0; y < COLS; y++){
cout << pd << endl;
for (x = 0; x <= zz; x++){
//cout << " | " << setw(16)<< setiosflags(ios::left) << pd [x][y]<< " | " << setw(5) << num << b << endl;
}
}
}
Grotesque Puppet
Aug11-05, 07:03 PM
Example
Number = 65536
log(65536)/log(2) = 16 bits = (16/8) bytes = 2 bytes
A 16-bit (2 byte) number ranges from 0 to 65535, or -32768 to 32767 depending if its signed or unsigned. To hold 65536 would require 17 bits.
Maybe I'm in the wrong place, but what the heck. In the basic tutorial, you mention that the int is usually 4 bytes. I don't know if it's something you want to get into, but it is compiler-dependent. I had occasion to use the Borland compiler a few years ago, and ints were all over the place. Sometimes they were longs, sometimes they were shorts, and I never did find a pattern to it. I finally gave up declaring ints at all and went straight to longs and shorts.
For what it's worth...
jim mcnamara
Oct12-05, 10:25 AM
The same problem obtains in a 64 bit environment where longs are 64 bits.
The Borland compilers are 16 bit, which is what MS-DOS and consumer Windows (Win95, Win98, WinME) are built on top of.
dduardo
Nov20-05, 09:35 PM
I finally finished the basic c++ tutorial. If your interested in a particular topic in programming let me know and i'll see if I can accommodate you.
exequor
Nov21-05, 09:54 PM
dduardo, it was a really good tutorial. Apart from the basics what else do you think would be good to know to solve problems using c++; such as for the acm programming contest? Do you plan to have an intermediate tutorial?
dduardo
Nov21-05, 10:13 PM
For the intermediate I'll do pointers, strings, basic classes, structures and file io.
Then for advanced I'll do overloading, polymorphism, virtual and templates.
I could also do a tutorial just on alorithms: sorting, trees, heaps, queues, stacks, etc.
I could also do special topics like posix threads, interprocess communication (IPC), x86 asm, etc.
In terms of ACM programming you would want a tutorial on dynamic programming. I know when I did ACM that was a big topic.
Which one do you want?
How about a topic covering math functions, Stuff like trigonometry and so on?
dduardo
Nov22-05, 06:36 AM
I could add math functions to intermediate and dynamic memory allocation to advanced.
Without putting too much pressure/workload on you dduardo :tongue2:, i would like to see as much included as possible to make the tutorial show most sides of c++ programming and the different aspects of it.
My suggestion is to try and cover as much as possible as clearly as possible as you have done so far. I like the fact that the posts are not several pages long but gives a more-than-basic idea about the specific topic and it is up to the reader to go and try for themselves a bit instead of reading every program code out of a book.
Great tutorial:biggrin:
eunhye732
Feb23-06, 02:17 AM
This is my first time using a C++ program...actually any programs. my C++ programming class is a lot harder than my physics and math classes. =(
i've never struggled so much so i would REALLY REALLY appreciate as much help as possible. here is my problem:
Write a program that asks the user how many numbers will be entered and then has the user enter those numbers. When this is done, report to the user the position of the first 7 entered and the last 7 entered. By position we mean, for example, that if the first 7 is the 2nd number entered then its position would be 2.
Sample screen output 1:
How many numbers will be entered? 8
Enter num: 5
Enter num: 7
Enter num: 6
Enter num: 7
Enter num: 7
Enter num: 3
Enter num: 8
Enter num: 6
The first 7 was in position 2
The last 7 was in position 5
Sample screen output 2:
How many numbers will be entered? 8
Enter num: 5
Enter num: 2
Enter num: 6
Enter num: 7
Enter num: 1
Enter num: 3
Enter num: 8
Enter num: 6
The first 7 was in position 4
The last 7 was in position 4
Sample screen output 3:
How many numbers will be entered? 8
Enter num: 5
Enter num: 1
Enter num: 6
Enter num: 5
Enter num: 9
Enter num: 3
Enter num: 8
Enter num: 6
Sorry, no sevens were entered.
All i know is that for the counter controlled loop, I use the For loop and include the if-else statement inside the loop. I just can't get the problem to tell me the positions for both 7s.
thanks again.
eunhye732
Feb23-06, 02:25 AM
if this was a wrong place to put my question, can you tell me where? Thanks
TenaliRaman
Feb23-06, 11:50 PM
I will do it by keeping two variables,
1. min_pos - will hold the position of first 7
2. max_pos - will hold the position of last 7
Steps :
1. Initialise min_pos and max_pos to -1
2. Whenever a 7 is read,
if min_pos = -1, update min_pos = counter
if counter > max_pos, update max_pos = counter
3. if both min_pos = -1, output no 7 was read
otherwise output min_pos and max_pos
Once you are done with the program, read the program carefully. Try to understand how the value of -1 was being used here. Such techniques are commonplace in many programs, so it should help you out.
-- AI
I need help with tutorial.I'am working a assigment 1.I enterd this in the Bloodshed Dev C++.
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
char myCharacter = 'z';
cout << "The datatype is" << sizeof(int) << " bytes!" << endl;
cout << " the varible has a value of " << myCharacter << endl;
return 0;
}
It works kind of.For some starge reason the box pops up but it closes as soon as it opens.
dduardo
Mar21-06, 07:58 PM
scott1, you can either run the application directly from thecommand line or add the following:
This should go at the top:
#include <cstdlib>
and this should go right before the return line:
system("PAUSE");
I'am working on the Pythegrom therom assigment.I need help
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int a = 'a', b = 'b', c = 'c';
cout << "Enter Length of A" << endl;
cin >> a;
cout << "enter length of b" << endl;
cin >> b;
a * a * b * b == c * c
cout << "c =" << c << endl;
system("PAUSE");
return EXIT_SUCCESS
It says there somthing worng with line 13 and 4 things with line 15 but I think there's probally more stuff worng with it then that.
dduardo
Mar23-06, 09:48 PM
Why are you doing a = 'a', b='b', c='c'?
Why don't you just do: double a, b, c;
Then the pythagorean theorem is simply c = sqrt(a*a+b*b) ;
remember to #include <cmath> for the sqrt function.
Is there ever going to be another more advance tutoril
I've dont this before and now I'm trying to do the hypotenuse thing again...here's what I've got:
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
double a, b, c;
a = sqrt(b*b+c*c);
cin >> b >> c;
cout << a;
system("PAUSE");
return EXIT_SUCCESS;
}
every time I run it a is equal to 0 EDIT: I'm stupid, I got it..
I the "cin" needs to go before the equation.
I have an exercise of building matrix class with characters: plus, subtract, divide, convert. Can you help me?:confused:
cworrier
Nov7-06, 04:45 PM
I suppose I may have posted this out of place, but it seemed to go beyond the tutorial. Here it is again.
I've been trying for days to get my boyfriend's C++ program to work, and I am almost ready to concede defeat, but I have frequented this site in the past as a lurker, actually learning a lot of what I know from the tutorials (thanks!).
Now, I have a problem I just can't seem to solve.
The object is to have the user pick a choose from a menu and have that value stored somewhere to be used by a function later. Once that choice is picked, the user needs to be able to pick another choice, until he or she fills in all three choices and then it's on to the formula! I also need a choice for clearing the data (I know how to set it all to 0) and one for quitting the program (just return 0; right?), as well as a display of the data that has been entered already once the formula calculates (I have this block of code written too). My formula works, but I'm not sure how to get all the values stored or how to let the user go back and pick a choice from the list after he or she has chosen one already.
Here's what I have so far, and it's a work in progress, but hopefully it's on the right track. I'm thinking I need to, maybe, use a switch statement for the menu, but I can't get that to work for me, and I'm still not sure how to store a value that's not going to be immediately used (maybe something with an array, but again I seem unable to produce the right code).
#include <iostream>
#include <math.h>
using namespace std;
doublemortgage (int c, double b, double a)
{
int i = c;
double j = b;
double k = a;
double l = b/(12 * 100);
double m = c * 12;
double result = k * (l / (1 - pow(1+l, -m)));
return result;
}
int main ()
{
int c;
double b;
double a;
double result;
int x;
cout << "Mortgage Calculation Menu \n";
cout << "1. Enter a Loan Amount \n";
cout << "2. Enter a Loan Rate \n";
cout << "3. Enter a Term in Years \n";
cout << "4. Calculate a Payment \n";
cout << "5. Clear All Input \n";
cout << "9. Quit \n";
cout << "Enter Your Selection: ";
cin >> x;
cout << " \n";
cout << "Enter a Loan Amount: $";
cin >> a;
cout << "Enter a Loan Rate: ";
cin >> b;
cout << "Enter a Term in Years: ";
cin >> c;
cout << "Your Monthly Payment: $"<< mortgage(c, b, a) << endl;
cout << " \n";
cout << "You Entered" << endl;
cout << "Loan Amount: $" << a << endl;
cout << "Loan Rate: " << b << "%" << endl;
cout << "Loan Term: " << c << "years" << endl;
cout << "Monthly Payment: $" << mortgage (c, b, a) << endl;
return0;
}
Is there a version of the getSubString function in c++? If so, what is it and what are the parameters?
-Thanks in advance
Freelancer
Jan22-07, 02:20 PM
alright, so im an Electrical Engineering major, and my current project requires me to program....
im using Visual STudio 2005, and im having a little trouble with just the basics...
here's my program so far:
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
int main
{
printf("heuy");
cout<< "hey";
return 0;
}
i run it, and all it gives me is a blank window....
it doesnt write anything....
can anyone help me?
neurocomp2003
Jan22-07, 04:09 PM
mmm ....did tha tcode actually compile???
my guess would be that your main call is missing something.
if it closes to fast put a pause statement like delay, getch, getchar.
I hope some of you will not understand may be the language i used in the brackets but are the swahili word so dont worry about it but what i do want to ask from your my friends is just the sammary of c programming language because am still learner of that language but also u can ask me about pascal programming language because somehow iam well on it i hope you will accept my request:surprised :surprised
hi my friends
i am a new in this side and i wana your help as fast as you can pleaaaaaaaas>>
the "q" is how to write the function in c++ if
x1=6 ,f(x)=x^2-4 and f'(x)=2x by using newton raphson method
and the next estimate of the root:
xk+1 = xk - f(xk) / f'(xk)
and the answer should be if i enter the (0.1):
- Enter precision (1/10, 1/100, 1/1000,...): 0.1
xk f(x) derived_f(xk) xk+1 dx
6.000 32.000 12.000 3.333 2.667
3.333 7.111 6.667 2.267 1.067
2.267 1.138 4.533 2.016 0.251
2.016 0.063 4.031 2.000 0.016
pleas dont be late>>>>>thanks
Nuclear on the Rocks
Apr11-07, 05:34 AM
which is better:
using c++ (graphics mode) or using Visual c++??
i'm sort of confused.
neurocomp2003
Apr11-07, 09:14 AM
Nuclear: graphics mode of what? opengl, directx, graphics.h??
trickae
Apr21-07, 11:00 AM
how viable would it be if we had a sticky on a pointers tutorial? Or a quick refresher - i always end up linking to wikipedia then a couple of college sites when explaining pointers over the net on forums (mostly code comments, cramster etc).
it'd be awesome if we can get a collaborative effort on making the best pointers tutorial on the net ...
if it sounds to geeky stop me right now ...
Equilibrium
May27-07, 10:03 PM
Help with assignment 4
Im trying to input a number with at least three digits:
heres what i did
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;
cout << "Enter a number:";
cin >> number;
cin.ignore();
if (number == setprecision(3) )
{
cout << "Number has 3 digits." << endl;
}
else
{
cout << "It is not a 3 digit number." << endl;
}
cin.get();
return 0;
somethings wrong and i know its the number == setprecision(3) what should i do?
by the way i just finished number 2 in assignment 4
please check and is there any other shortcut method ?
#include <iostream>
using namespace std;
int main()
{
char character;
cout << "Enter any letter from A to Q: ";
cin>>character;
cin.ignore();
switch (character) {
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
cout << character;
break;
default:
cout << "Letter not in the list. " << endl;
}
cin.get();
return 0;
}
Equilibrium
May28-07, 12:59 AM
dduardo's Assaignment # 5
Hey i need help with this one..
kindly explain with detail?
i also found this on another forum
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int pascal(int row, int col)
{
if (row == 0 || col == 0 || row == col + 1)
return 1;
return pascal(row - 1, col - 1) + pascal(row - 1, col);
}
int main(void)
{
int n;
cout << "Enter Row: ";
cin >> n;
cin.ignore();
for (int i = 0; i <= n; ++i) {
for (int j = 0; j < i; ++j)
cout << pascal(i, j) << " ";
cout << endl;
}
cin.get();
return 0;
}
they are using the code pascal which is not explained in dduardo's tutorial
I briefly looked over the C++ tutorial, and it looked fairly good. One thing though - maybe you should mention the Code::Blocks IDE (http://www.codeblocks.org), and that if one decides to use it, they should use the latest Nightly Build. Although Dev-C++ is still pretty good, it is getting old, and Code::Blocks is becoming better and better than it.
MeJennifer
Jun2-07, 02:28 PM
by the way i just finished number 2 in assignment 4
please check and is there any other shortcut method ?
There is, since the requested range of letters is simply a range of ASCII codes.
dduardo's Assaignment # 5
Hey i need help with this one..
kindly explain with detail?
i also found this on another forum
they are using the code pascal which is not explained in dduardo's tutorial
"pascal" is a user-defined function.
Hmm...recursion in C/C++ is often inefficient and can lead to memory problems....
hows this for the hypotenuse assignment?
#include <iostream>
#include <conio.h>
#include <iomanip>
#include <cmath>
using namespace std;
main()
{
long double num1, num2, num3;
int number, num4, reset = 1;
do {
cout << "1. Hypotenuse" << endl << "2. Other" << endl;
cin >> number;
switch (number) {
case 1:
cout << "Enter the two sides, each followed by the enter key" << endl;
cin >> num1 >> num2;
num2 = sqrt(num1*num1 + num2*num2);
break;
case 2:
cout << "Please enter the hypotenuse" << endl;
cin >> num1;
cout << "Please enter the other side" << endl;
cin >> num2;
num3 = sqrt(num2*num2 - num1*num1);
cout << num3 << endl;
break;
}
num3 *= 1000;
num1 = num3 - floor(num3);
num1 *= 10;
num1 = floor(num1);
if (num1 >= 5) {
num3 = ceil(num3);
} else {
num3 = floor(num3);
}
num3 /= 1000;
cout << "Thankyou, the desired length is: " << num3 << " to 3d.p." << endl;
cout << "Would you like to reset? (1 to reset)" << endl;
cin >> reset;
} while ( reset == 1);
return 0;
}
edit:
i have improved it, with menu system and other side calculation but im having trouble getting a big enough variable to hold a number bigger than 9 aswell as with 3 or more decimal places..... it seems long double isnt enough...
what should i be using?
still have no idea about the 3 digit assignment...
p.s. for the 3 digit assignment... can it just be eg "482" or should it include things like 4.82?
equilibrium.. the shorter way is to just say
if ((num2 > 'a' && num2 < 'q') || (num2 > 'A' && num2 < 'Q')) {
cout << "yes\n";
} else {
cout << "no\n";
}
and for pascal, i created my own functions and then fiddled to troubleshoot. i had the program automatically enter row 0 and then i set the first position of each row to 0...
but still i dont even know where to start on the 3 digit one...
moe_3_moe
Jun26-07, 02:42 PM
"assignment 1.cpp": W8057 Parameter 'argv' is never used in function main(int,char * *) at line 10???????????
moe_3_moe
Jun26-07, 02:43 PM
i didn't understand argv and argc????
moe_3_moe
Jun26-07, 02:43 PM
"assignment 1.cpp": W8057 Parameter 'argv' is never used in function main(int,char * *) at line 10
saket1991
Jun30-07, 09:47 AM
I need help on two questions......
1)Is C different from C++?If yes then in what ways?
2)Can someone plz show me a link to download C/C++ for free??
saket1991:
1. Yes, C is different from C++. C is pretty much (but not completely) a subset of C++. C++ is basically C with object-oriented features.
2. You don't really download C/C++. You can download a C/C++ compiler, linker, and editor, or an IDE (integrated development environment - pretty much combines the compiling, linking, and editing processes) . If you're using windows, you might want to try Dev-C++ or Code::Blocks (if you choose to use Code::Blocks, I recommend getting the latest Nightly build (http://forums.codeblocks.org/index.php?board=20.0) - read the stickied threads at the link for more information on using Nightly builds). Dev-C++ and Code::Blocks are both IDEs, by the way.
Yersinia Pestis
Jul12-07, 05:49 PM
First off, dduardo, thank you for what has been, so far, a most excellent tutorial.
Having said that, the pascals triangle task has seemed daunting to me, and I had to look up how to make my own functions to do it efficiently, and I came up with this:
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
long double factorial (int num)
{
if (num==1)
return 1;
return factorial(num-1)*num; // recursive call
}
int pscl (int n, int r)
{
int out;
long double nf=factorial(n), rf=factorial(r), nrf=factorial(n-r);
long double btm=rf * nrf;
long double tout=nf/btm;
out = (int)tout;
return out;
}
int main(int argc, char *argv[])
{
int rin;
int nin;
int pout;
cout << "input row: ";
cin >> rin;
cout << "input number: ";
cin >> nin;
pout=pscl(nin, rin);
cout << pout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
the function 'factorial' is fairly obvious, and is a double float because factorials can be big. 'pascal' uses the binomial coefficient thing to calculate the number at a given place and row (n, r).
but this code crashes, and the debugger (when it decides to work) tells me it gets an 'access violation'. I tried breakpoints, but as I said, the debugger is a bit temperamental. Can you see anything wrong with my code?
No idea what the original question were, but I can tell you your program is crashing because / when the end user is entering a number for 'rin' that's larger than 'nin'. I.e. when 'n-r' < 0. (It might also crash when n-r == 0, but too lazy to try.)
Yersinia Pestis
Jul12-07, 09:56 PM
Could you be kind enough to explain why it's crashing when n-r==0 ?
EDIT: I changed the condition for the if statement in 'factorial' to (num==1 || num==0) and now it works fine. I'm never nicking code off the internet again.
Thanks for bringing it to my attention. I can't believe I didn't spot that after going over the problem for 40 minutes.
Yersinia Pestis
Jul13-07, 02:11 AM
Well, I've finished the tutorial. Again, great material dduardo.
But the open goal at the end seems a bit steep. A text adventure? With out object-orientation? But, I guess it's a challenge.
Except i ran into a major hurdle. Text inputs. This code:
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
char inp[256];
cin >> inp ;
cout << inp << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Only seems to grab input up to the first space. How can I get the whole string that is entered?
Also, did the other parts to the tutorial get thrown in the bin? If so, is there anywhere I can look for the higher levels of C++ programming?
#include <iostream>
#include <string>
int main()
{
std::string s;
std::getline(std::cin, s);
std::cout << s << std::endl;
}
Yersinia Pestis
Jul13-07, 03:03 AM
Thanks man! I'm gonna makes me a text adventure!
And look for more C++ stuff that's got stuck in the tubes.
i.mehrzad
Jul25-07, 03:04 AM
I know nothing in programming and wanted to know that is this the right place to start as i am finding it a little difficult.
archermcr
Sep2-07, 10:31 PM
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
int x,j;
double N,T,S,D,X;
cout<<"Enter Value of x:"<<endl;
cin>>x;
cout<<"Enter No. of Iterations:"<<endl;
cin>>j;
cout<<endl;
X=(x*3.1416)/180; //conversion from degrees to rad
N=X; //inital value
D=1; //inital value
T=1; //inital value
S=1; //inital value
cout<<"i"<<"\t\t"<<setw(6)<<"Term"<<"\t\t"<<"cos("<<x<<")"<<endl;
cout<<endl;
for(int i=1;i<=j;i++)
{
N=(-N)*X*X;
D=D*(2*i)*((2*i)+1);
T=N/D; //term
S=S+T; //summation
cout.setf(ios::fixed|ios::showpoint|ios::left);
cout<<i<<setprecision(3)<<"\t\t"<<T<<"\t\t"<<setprecision(5)<<S<<endl;
}
cout<<endl;
cout<<endl;
cout<<"sin("<<x<<")"<<"="<<S<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
i derived the formula from the expansion of the function of sin(x) which is
x-(x^3/3!)+(x^5/5!)-(x^7/7!)... pls help me..whats wrong w/ my program =(..it wont seem to display the cortrect value..
Why don't u separate the code for searching the factorial of n (n!) in another function.....it will be much easier to debug.......
chaoseverlasting
Jan3-08, 04:07 AM
If you write out the code for calculating factorial separately, and use cmath(for the pow() function), you could do it like this:
s=0;
for(int i=1;i<=j;i++)
{
s+=pow(-1,i+1)*pow(x,2*i+1)/fact(2*i+1);
};
cout<<"sinx= "<<s;
where pow(a,b)=a to power b, and fact(x) =x!
bleeker
Jun12-08, 08:03 AM
Will C or C++ work better to program a pic?
Will C or C++ work better to program a pic?
Well, It can be wrong but I think C would be better, since it is an event driven programming language and it work faster, in more efficient way.
Ben Niehoff
Jul4-08, 12:53 PM
First off, dduardo, thank you for what has been, so far, a most excellent tutorial.
Having said that, the pascals triangle task has seemed daunting to me, and I had to look up how to make my own functions to do it efficiently, and I came up with this:
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
long double factorial (int num)
{
if (num==1)
return 1;
return factorial(num-1)*num; // recursive call
}
int pscl (int n, int r)
{
int out;
long double nf=factorial(n), rf=factorial(r), nrf=factorial(n-r);
long double btm=rf * nrf;
long double tout=nf/btm;
out = (int)tout;
return out;
}
int main(int argc, char *argv[])
{
int rin;
int nin;
int pout;
cout << "input row: ";
cin >> rin;
cout << "input number: ";
cin >> nin;
pout=pscl(nin, rin);
cout << pout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
the function 'factorial' is fairly obvious, and is a double float because factorials can be big. 'pascal' uses the binomial coefficient thing to calculate the number at a given place and row (n, r).
but this code crashes, and the debugger (when it decides to work) tells me it gets an 'access violation'. I tried breakpoints, but as I said, the debugger is a bit temperamental. Can you see anything wrong with my code?
Ack! There are FAR more efficient ways to calculate Pascal's triangle than to use a factorial function. I think the Mathworld page failed to explain the key property of Pascal's Triangle, which was Pascal's original motivation in the first place:
The numbers in each row are obtained by adding the two numbers above them in the previous row.
The Wikipedia page has a much better explanation: http://en.wikipedia.org/wiki/Pascal%27s_triangle
Maybe you should try re-writing your program not using any factorial function. Even a long double will not be big enough for you to get a triangle more than 20 rows or so. And it will also be inaccurate due to rounding errors (a double only holds 15 significant digits of accuracy; it represents higher numbers by using scientific notation).
If you use a more efficient method (simply summing terms from the previous row), then you can create huge triangles using only ints, and your program will run much, much faster.
Malvenuto
Aug2-08, 07:24 PM
Assignment 3 requires use of the sqrt() function and the math.h library. The tutorial before that point doesn't mention them. Not sure whether or not you meant to leave them for the reader to find out on his own, but if not it might make sense to add them.
computerex
Aug3-08, 02:36 AM
Well, It can be wrong but I think C would be better, since it is an event driven programming language and it work faster, in more efficient way.
C is procedural, not event driven.
Can anyone please try to see what's wrong with this program? I wrote it for school, to help simply radicals. It seems to work fine most of the times. However there is a problem when trying to simply perfect cubes. Try and entering 64 with an index of 3, it'll give you an unexpected answer. Now try entering 8 with an index of 3, and it'll give you the right answer. I have tried debugging it, but it's not making any sense to me. I am sorry if this shouldn't be posted here, let me know and I can move it. :)
#include <iostream>
#include <math.h>
typedef struct
{
double x, y;
}pair;
bool breakcube(double radi, double inx, pair& pr)
{
double cb = 0;
for (int i = 2; i < radi; i++)
{
cb=i;
for (int j = 1; j < inx; j++)
cb*=i;
for (int j = 1; j < radi; j++)
{
if (cb*j==radi)
{
pr.x = cb;
pr.y = j;
return true;
}
}
}
return false;
}
int main()
{
double radi = 0;
double cb = 0;
double inx = 0;
char buff[500];
while(true)
{
std::cout << "\nEnter radicand ('quit' to terminate): ";
std::cin >> buff;
if (!strcmp(buff, "quit"))
return 0;
radi=atof(buff);
std::cout << "\nEnter index: ";
std::cin >> inx;
cb = pow(radi, 1.0/inx);
if (cb == (int)cb)
{
std::cout << "\nPerfect " << inx << " : ";
for (int i = 0; i < inx; i++)
{
std::cout << cb;
if (i!=inx-1)
std::cout << " * ";
}
std::cout << " = " << pow(cb, inx);
continue;
}
pair pr;
if (breakcube(radi, inx, pr))
std::cout << "\n" << radi << " can be broken by: " << pr.x << " * " << pr.y;
else
std::cout << "\n" << radi << " cannot be broken";
}
return 0;
}
Malvenuto
Aug3-08, 08:04 PM
In Exercise 5, the do-while example code prints out HELLO only twice instead of the 3 times shown in the example output.
robertkurti
Sep8-08, 08:56 PM
guys can somebody help me with a java programming? It's a really short homework but I'm just stucked there. Here is the code if u can please teplay to me asap.
public class DaysPerWeek
{
public static void main(String[] args)
{
final int DAYS_PER_WEEK = 7;
int days;
int weeks;
int totalDays;
Scanner scan = new Scanner(System.in);
System.out.println("This program convert days to week");
System.out.print("Enter number of days; ");
days = scan.nextInt();
days = totlaDays % DAYS_PER_WEEK;
weeks = totalDays / DAYS_PER_WEEK;
System.out.println("Days Per Week" + totaldays);
}
}
dtsylvas
Sep24-08, 11:28 PM
I have a question about my C++ program....I have to compute the area of a rectangle.....I have to write this program using functions....I have my instructions correctly output to the user in the command prompt and I am allowing the user to enter in a value for the length and the width....that's all fine....I wrote the computation for the solution to the problem but the cout info to appear on the screen but that part does not show up along with the answer.....can anyone help me?
ehrenfest
Oct3-08, 10:56 PM
My C++ is a little rusty. I want to have a class that has a 3 by 3 array of integers as a member variable. I want the class to return the array through a member function. I am having trouble getting the initialization right. I think you can tell what I want to do from the following program although of course the compiler would go crazy if I tried to compile this. Can someone please tell me how to rewrite this so it is correct?
class MyClass
{
public:
//this function should return the array
int * MyFunction(){
return my_array;
}
//default constructor
MyClass(){
my_array = {{1,2,3},{4,5,6},{7,8,9}};
}
private:
int my_array [3][3];
}
ehrenfest
Oct3-08, 11:51 PM
Hmmm. I think they kind of provide a solution at the MSDN website:
http://msdn.microsoft.com/en-us/library/2xfh4c7d.aspx
I have a few questions about that...does anyone understand what they are doing there?
ammenme
Oct25-08, 11:39 AM
hi please i download textpad for my computer to use it for c++ but in the tool box i cant find the compile tool.please any help.thanks
John_Phillips
Oct29-08, 12:47 AM
For ehrenfest - For your first question, the trouble you have is about the return type. You are returning a pointer to integers. That will work for one dimensional arrays, but not for higher dimensional arrays. Your 3 by 3 array is actually a pointer to pointers to integers. That is, the first pointer has an array of other pointers. The lower level pointers each have arrays of three integers. So, you could make the return type usable by making it a pointer to pointers.
That said, I would suggest against doing it. What you are returning is a direct access into the memory held by the class. Anyone who makes a change to this return value is changing the contents of the object, and not just some local version of the array. Even worse, the object could be destroyed (by going out of scope, for example) and leave you with a pointer that no longer points where you think it points. This is a seg fault or other corruption waiting to happen. Reconsider why you want to do this. It may be that the return doesn't help you and you really want a copy constructor or an accessor function. It may be that you don't really want the safety of encapsulating the data. In which case, it is a better design idea not to try and fake safety that isn't really there.
As for your second question - they are working with managed memory containers in the visual compilers. Only try to follow them if you do not ever need to use this for anything other than the visual platform.
John
ammenme
Oct29-08, 03:15 AM
so am i to download the visual c++ separately and add it to the text pad or i can use the visual c++ without text pad?thanks
Hello:
I am using MS Visual Studio as the compiler. I have a c++ routine that I needed in my current project, which I saved under my Header Files. This file is needed for the compiler to interpret certain variable declarations. However, when I F7 to compile I get the following error:
Cannot open include file: 'nr3.h': No such file or directory
But I can clearly see the nr3.h file in my project. What is wrong? Please find my code below:
#pragma once
#include "nr3.h"
class gamma
{
Doub gammln(const Doub xx) {
.
.
.
}
Main program:
#include "gamma.h"
#include "incgammabeta.h"
#include "nr3.h"
using namespace std;
int main()
{
double a, b, x, incompleteBeta;
.
.
.
return 0;
}
John_Phillips
Nov3-08, 09:06 AM
Is the directory that holds the nr3.h header in your include paths? That is the typical cause of this error.
John
Rancour
Feb20-09, 07:43 AM
Hello, I am a beginner to C++ and I have a couple of inquiries on the subject. First, do I have to be a mathematician to program C++? And lastly, if so, what mathematical knowledge must I have?
John_Phillips
Feb20-09, 09:23 AM
No, you don't.
Any programming requires you to think algorithmically, and that is a skill mathematicians tend to have, but you don't have to be a mathematician to program.
John
Rancour
Feb20-09, 06:28 PM
No, you don't.
Any programming requires you to think algorithmically, and that is a skill mathematicians tend to have, but you don't have to be a mathematician to program.
John
Thanks John, that cleared some stuff up for me. I'm not bad at math, but I'm not all that good....Does any one else know of any mathematics I may need, besides arrays?
hey, i dont think you need any maths beyond the basics at school for programming, its more about being able to plan your program out in your head and work out how your going to do it, then you can get into the nitty gritty and google most of the stuff you have trouble with :P
you dont even have to understand what a mathematical array is. you can just think of one as like an excel sheet :P
logical laying of stuff out i guess is why it suits mathematicians :P
what kinda things do you want to learn from your programming? ive done a fair bit now in some pretty different languages, and C++ may not necessarily be the best thing to start with for you... if you want to make applications with windows and things, VB or C# could be a good place to start; its pretty and easy. i dont know what everyone else thinks?
Rancour
Feb20-09, 10:19 PM
hey, i dont think you need any maths beyond the basics at school for programming, its more about being able to plan your program out in your head and work out how your going to do it, then you can get into the nitty gritty and google most of the stuff you have trouble with :P
you dont even have to understand what a mathematical array is. you can just think of one as like an excel sheet :P
logical laying of stuff out i guess is why it suits mathematicians :P
what kinda things do you want to learn from your programming? ive done a fair bit now in some pretty different languages, and C++ may not necessarily be the best thing to start with for you... if you want to make applications with windows and things, VB or C# could be a good place to start; its pretty and easy. i dont know what everyone else thinks?
Okay, that makes sense as well :D what about Python as a first language? I also dug up an old book on QBasic. is it good to learn this as a first language for organization etc...? or is Python better for a first?
EDIT: Also I heard that Ruby is making improvements with speed, would this be better over python for a first?
Okay, that makes sense as well :D what about Python as a first language? I also dug up an old book on QBasic. is it good to learn this as a first language for organization etc...? or is Python better for a first?
EDIT: Also I heard that Ruby is making improvements with speed, would this be better over python for a first?
hey, well i first learnt to program using pbasic, this is used to program picaxe microcontrollers, really basic stuff. i guess qbasic might be similar...
i first learnt to program a computer using a program called autohotkey, its really easy to use
then i did a project using visual basic 6 (old stuff) and picked that up fairly quickly
im now doing a project on C# and finding that not so bad after my previous experience
once you know how to structure a program, the toughest challenge is finding the right commands and understanding the concepts of new languages. (eg, i can understand/program the nitty gritty of a C# program, but i get my head in a twist when it comes to putting that code into methods and how to declare things).
try qbasic, im not sure how bad it is. or have a go at autohotkey and pm me if u need any help.
another thing i find when learning to program is: always try and set yourself a target. dont just program lines together. think of something cool you could do with the language (have a read of the introduction first so you know your not gonna be stretching what is possible with it). that way, even though you might be guessing a bit at first, you learn very fast what goes where and i find the understanding of stuff comes later (eg methods in C#, i had no idea, but i get it now :P)
big jump from something like pbasic to visual basic etc is you never use the 'goto' command in VB, thats the basic of object orientated programming.
edit: oh and look at example code in the language, youll probably find yourself doing this alot as you search for something and find an example script. looking helps you keep with the conventions, and speeds up the learning curve. its probably best to create a new "programming" folder now!
asma_MIT
Jun30-09, 09:07 AM
hello what are the real n imaginary numbrz in c++ classes definng our own operators
HallsofIvy
Jun30-09, 12:21 PM
In the standard C++ library, the type "complex" is defined as
complex(
const Type& _RealVal = 0,
const Type& _ImagVal = 0
)
There is no "real" except as referring to the real part, _RealVal, of a complex number. Real numbers are represented as "int", "float", or "double".
god i am getting into computer science myself.um can i learn the basics of c++here
vBulletin® v3.7.6, Copyright ©2000-2009, Jelsoft Enterprises Ltd.