In summary, dduardo provides a summary of the content in the following conversation. He also provides a suggestion for clarification.
  • #106
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.
 
Last edited:
Technology news on Phys.org
  • #107
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:
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?
 
  • #108
Code:
#include <iostream>
#include <string>

int main()
{
    std::string s;
    std::getline(std::cin, s);
    std::cout << s << std::endl;
}
 
  • #109
Thanks man! I'm going to makes me a text adventure!

And look for more C++ stuff that's got stuck in the tubes.
 
  • #110
i know nothing in programing

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.
 
  • #111
Hey Guys can you help me w/ my algorithm for sin(x), the correct value won't appear

#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 won't seem to display the cortrect value..
 
  • #112
Why don't u separate the code for searching the factorial of n (n!) in another function...it will be much easier to debug...
 
  • #113
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!
 
  • #114
Will C or C++ work better to program a pic?
 
  • #115
bleeker said:
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.
 
  • #116
Yersinia Pestis said:
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:

Code:
#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's_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.
 
  • #117
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.
 
  • #118
soul said:
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. :)

Code:
#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;
}
 
Last edited:
  • #119
In Exercise 5, the do-while example code prints out HELLO only twice instead of the 3 times shown in the example output.
 
  • #120
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);
}

}
 
  • #121
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?
 

Attachments

  • area.doc
    28 KB · Views: 240
Last edited:
  • #122
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?

Code:
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];

}
 
  • #124
hi please i download textpad for my computer to use it for c++ but in the tool box i can't find the compile tool.please any help.thanks
 
Last edited:
  • #125
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
 
  • #126
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
 
  • #127
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;
}
 
  • #128
Is the directory that holds the nr3.h header in your include paths? That is the typical cause of this error.

John
 
  • #129
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?
 
  • #130
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
 
  • #131
John_Phillips said:
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 anyone else know of any mathematics I may need, besides arrays?
 
  • #132
hey, i don't 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 don't 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? I've 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 don't know what everyone else thinks?
 
  • #133
samski said:
hey, i don't 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 don't 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? I've 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 don't 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?
 
Last edited:
  • #134
Rancour said:
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 learned to program using pbasic, this is used to program picaxe microcontrollers, really basic stuff. i guess qbasic might be similar...

i first learned 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, I am 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. don't 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 going to 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, that's the basic of object orientated programming.

edit: oh and look at example code in the language, youll probably find yourself doing this a lot 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!
 
  • #135
hello what are the real n imaginary numbrz in c++ classes definng our own operators
 
  • #136
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".
 
  • #137
god i am getting into computer science myself.um can i learn the basics of c++here
 
  • #138
pep_i said:
god i am getting into computer science myself.um can i learn the basics of c++here

I think you can the basics of C++, but you should get a book to understand it fully.
 
  • #139
i want help in Numerical integration programing by C
 
  • #140
lulu f said:
i want help in Numerical integration programing by C

Um, do you mean numerical approximation? Please be more specific.
 
Back
Top