C/C++ Guide to C++ Programming For Beginners

Click For Summary
The discussion focuses on a beginner's guide to C++ programming, emphasizing the importance of selecting a suitable integrated development environment (IDE), such as Bloodshed’s Dev-C++, for compiling and debugging code. Participants express appreciation for the tutorial's structure and suggest including deeper explanations of key concepts like conditional statements, iterative statements, and pointers. There is a request for clearer code examples to enhance understanding, particularly regarding function definitions and the use of header files. The conversation also touches on the potential for future tutorials on GUI toolkits and advanced topics. Overall, the thread serves as a collaborative platform for sharing insights and improving the learning experience in C++.
  • #91
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 ...
 
Technology news on Phys.org
  • #92
Help with assignment 4

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;
}
 
Last edited:
  • #93
Pascal's triangle

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
 
  • #94
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.
 
  • #95
Equilibrium said:
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.
 
  • #96
Equilibrium said:
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...
 
  • #97
hows this for the hypotenuse assignment?

Code:
#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 I am having trouble getting a big enough variable to hold a number bigger than 9 as well as with 3 or more decimal places... it seems long double isn't enough...

what should i be using?

still have no idea about the 3 digit assignment...
 
Last edited:
  • #98
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
Code:
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 don't even know where to start on the 3 digit one...
 
  • #99
"assignment 1.cpp": W8057 Parameter 'argv' is never used in function main(int,char * *) at line 10??
 
  • #100
i didn't understand argv and argc?
 
  • #101
"assignment 1.cpp": W8057 Parameter 'argv' is never used in function main(int,char * *) at line 10
 
  • #102
I need help on two questions...
1)Is C different from C++?If yes then in what ways?

2)Can someone please show me a link to download C/C++ for free??
 
  • #103
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 - 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.
 
Last edited:
  • #104
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?
 
  • #105
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.)
 
  • #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:
  • #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);
}

}
 

Similar threads

  • · Replies 8 ·
Replies
8
Views
5K
  • · Replies 27 ·
Replies
27
Views
6K
  • · Replies 3 ·
Replies
3
Views
4K
Replies
5
Views
7K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 8 ·
Replies
8
Views
5K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 13 ·
Replies
13
Views
6K