C++ Programming Basics: A Walkthrough Tutorial

  • C/C++
  • Thread starter PainterGuy
  • Start date
  • Tags
    C++
In summary: again. argc and argv are the same as what you use in your main function. argc is the number of arguments passed to your program, and argv is an array of strings, each containing one argument.std::cout is a function that prints a string.std::cin is a function that prints a number.std::iostream is a function that prints both a string and a number.using namespace std; tells the compiler that you are using the standard namespace. this makes programming easier as you don't need to put a reference to the namespace at each function call; the compiler will already know.
  • #1
PainterGuy
940
69
hello guys,

i have downloaded dev-c++ as suggested by some nice guys around here. from today i will start practcing with comuter programming. me know nothing about programing but sure will learn it with the help of this forum.

okay. i have opened new project named "gorilla" in dev-c++. it is showing me lines:


#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
system("PAUSE");
return EXIT_SUCCESS;
}



kindly tell me what are these automatic lines. and can you tell of some site where i can download sample console based c++ programms. will continue this thread. your help is needed and appreciated.

cheers
 
Technology news on Phys.org
  • #2
painterguy said:
#include <cstdlib>
#include <iostream>
Those two statements are inclusions of various packs that make programming with C++ a lot easier. The cstdlib, is the C Standard Library, it includes various commonly used functions, and iostream is the Input Output Stream, which includes functions like cout and cin, which are present in nearly every c++ program.
using namespace std;
This essentially tells the compiler that you are using the standard namespace, this makes programming easier as you don't need to put a reference to the namespace at each function call; the compiler will already know.
ex. Without using namespace std:
Code:
std::cout
with:
Code:
cout

If you go far enough with C++ you will be able to make your own namespaces eventually.

int main(int argc, char *argv[])
{
system("PAUSE");
return EXIT_SUCCESS;
}

I'm not entirely sure why those arguments in int main are there, but I know a lot of compilers have them when you start with a prefilled program.

The system pause, I assume, would make the program pause before it immediately terminates after running your program so you can view your output.

The return success statement is basically a statement to tell you or the compiler that everything ran correctly.

These prefilled programs aren't the greatest. When I start a program, I usually just start it with this code:

Code:
#include <iostream>
using namespace std;

int main()
{


return 0; //This is another way of writing return EXIT_SUCCESS;
}

It's a little bit easier to read and understand, but it doesn't really matter.
 
  • #3
KrisOhn said:
This essentially tells the compiler that you are using the standard namespace, this makes programming easier as you don't need to put a reference to the namespace at each function call; the compiler will already know.
ex. Without using namespace std:
Code:
std::cout
with:
Code:
cout[/COLOR]



hi KrisOhn,

a lot of thanks to help me in this and many other problems. you are really good. what is "namespace" in c++? would you please mind explaining the highlight part? much thanks again
 
  • #4
argc is the number of arguments passed to your program, and argv is an array of strings, each containing one argument.
 
  • #5
painterguy said:
what is "namespace" in c++?
http://en.wikipedia.org/wiki/Namespace

A namespace is essentially a place where you store function definitions. You can define the function in the namespace file, then you can put references to that namespace whenever you call the function. When the compiler comes up to the function, it will not know what to do with it, but if you put the reference to the namespace, it will look in the namespace for a function definition, that will tell it how to act.

Example:

I have a namespace, SPACE, where I define a function ABC. In my main function I have the function call, ABC(x, y). Since that is a function I created, the compiler will not know what to do with it when it comes up to it. So to get around this, I need to tell the compiler where the function definition is located, I do this by putting a reference to the namespace file; like so:
SPACE::ABC(x, y)
Then the compiler will know that the function definition is in the SPACE namespace.

would you please mind explaining the highlight part? much thanks again

By 'Without using namespace std', I mean if you were to not include the
Code:
 using namespace std;
line at the top of your program. And by 'with', I mean if you do include that line at the top of your program.
 
  • #6
many many thanks KrisOhn. u r really good and helped me with many problems. hope learn a lot of programing from you. see now have started to use proper english sentences after you advice me!


see you mentioned wikipedia. a lot of information is available on wikipedia and internet in general but you see problem some time that information is hard to find by everyone, specially by non-english speaker. then those things are hard to undertsnad for beginners. then most important of everything is that every person learn in different way and have different questions which they want answers for before they go any further.


now this is about programming. when me include "using std namespace". does me tell compiler that me want the compiler to include all standard built in functions? what are these standard built in functions? are these math functions? little explanation is enough for me. many thanks to you to help me to walk through this c++ journey.
cheers
 
  • #7
No problem with the help, it's my pleasure.

painterguy said:
when me include "using std namespace". does me tell compiler that me want the compiler to include all standard built in functions? what are these standard built in functions? are these math functions?

Yes, when you include the statement 'using namespace std;', it tells the compiler where to look for standard function definitions.

As long as you start each program with
Code:
#include <iostream>
using namespace std;
you will probably have no trouble with the introductory programming that you will be doing. These include probably nearly every function that will be used in a normal program, not including math functions.

To include math functions you must include another statement at the top of your program:
Code:
#include <cmath>
 
  • #8
many thanks KrisOhn. you are really helpful. me hope you would continue to help me to walk this walk. the good thing is now me taking english learning very serious. have started using english. this forum site is really cool. hope will learn many things from nice people here.

cheers
 
  • #9
hello again,

me have made some very simple console programs. sorry, can not post code right now using internet on my mobile phone. but big bad thing about these console programs is that they work step by step. for example me made program to add sum of four numbers a,b,c,d. first console say enter "a", then "b"... problem is when me have entred "a" then there is no previous record. it's like one step in one moment. is this possible to make console programe in such way that it appears in the way it keep record of previous statements. for example in case of my program when me have entered "a" and it asks for "b". but above th line where it says "enter b" it shows that "a=(whatever value)". me means as me proceed with entering the value for variables me have written record appearing of the previous entered values. me hope you understand what me try to say. me grateful for every help.

cheers
 
  • #10
painterguy said:
hello again,

me have made some very simple console programs. sorry, can not post code right now using internet on my mobile phone. but big bad thing about these console programs is that they work step by step. for example me made program to add sum of four numbers a,b,c,d. first console say enter "a", then "b"... problem is when me have entred "a" then there is no previous record. it's like one step in one moment. is this possible to make console programe in such way that it appears in the way it keep record of previous statements. for example in case of my program when me have entered "a" and it asks for "b". but above th line where it says "enter b" it shows that "a=(whatever value)". me means as me proceed with entering the value for variables me have written record appearing of the previous entered values. me hope you understand what me try to say. me grateful for every help.

cheers
The "console" is just the command window that your program runs in. I would have to see your code to understand the problem you're having. When you get a chance, post your code so we can take a look.

Lesson on pronouns

"me have made some very simple console programs."
"for example me made program ..."
You should say "I have made some very simple console programs." and "for example I made a program ..."

When the 1st person singular pronoun is the subject of the sentence, use "I", as in the examples above.
To show possession, use "my", as in "My program adds four numbers."
When the 1st person singular pronoun is the object of the action, use me, as in "The instructor gave me some help with this program."
 
  • #11
Mark44 many thanks for your guidelines on pronouns. since i join this forum trying to use proper english as much as possible. it take much time time even to write single post bcause i think many time before writing a single only word. after reading your help on pronouns i looked also my grammar book. you are correct. i will try to take care of this misuse again. much grateful for teaching me this. i am still using internet on my phone. will post code as i start using my computer again. you people are really good and considerate.

cheers
 
  • #12
Mark44 said:
The "console" is just the command window that your program runs in. I would have to see your code to understand the problem you're having. When you get a chance, post your code so we can take a look.


Mark44 said:
The "console" is just the command window that your program runs in. I would have to see your code to understand the problem you're having. When you get a chance, post your code so we can take a look.

hello,

now i am on my computer. when i wrote this code on my friend's computer it worked. now some thing is wrong here. this is code:

{
float a, b, c, Average;
std::cout << "Enter first number: ";
std::cin >> a;
std::cout << "Enter second number: ";
std::cin >> b;
std::cout << "Enter third number: ";
std::cin >> c;
std::cout << "The average is: " << (a + b + c) / 3;
}



you can look at image attached to see error. these lines are always present in dev-c++ when in start it:

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
system("PAUSE");
return EXIT_SUCCESS;
}

please tell me what wrong has happened. your help is appreciated. many thanks
 

Attachments

  • first program.jpg
    first program.jpg
    48.5 KB · Views: 408
  • #13
Look at the compiler errors at the bottom:

declaration of C function int main() conflicts with previous declaration int main(int, char **)

delete the first declaration of main (the entire function) and it will work.
 
  • #14
DavidSnider said:
Look at the compiler errors at the bottom:

declaration of C function int main() conflicts with previous declaration int main(int, char **)

delete the first declaration of main (the entire function) and it will work.

sorry this does not work. i removed that int line. please see at image.

cheers
 

Attachments

  • first program2.jpg
    first program2.jpg
    46.9 KB · Views: 448
  • #15
Remove the entire function, not just the line.

Also, in the future please post your code, not a screenshot.
 
  • #16
Alternatively, you could have used the code template that was provided to you, inserting your code in the main function that was provided to you.

Code:
int main(int argc, char * argc[])
{
   // Put your code here
   // float a, b, c, Average;
   // ...

   // Code in template for main()
   system("PAUSE");
   return EXIT_SUCCESS;

The problem was that you had two main() functions. You can have only one.
 
  • #17
hello nice people,

DavidSnider and Mark44 thanks for giving me hints. DavidSnider see now i have include my code within code braces.:smile:

Code:
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
	float a, b, c, d, Mean;
	std::cout << "Enter first number: ";
	std::cin >> a;
	std::cout << "Enter second number: ";
	std::cin >> b;
	std::cout << "Enter third number: ";
	std::cin >> c;
	std::cout << "Enter fourth number: ";
	std::cin >> d;
	std::cout << "The mean is: " << (a + b + c + d) / 4; 
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

i have attached screenshot of running program. the first program made by me. i am happy! in screenshot you can see there is no space between "61" and "Press any key to continue...". how can i create space?

second thing is when i press any key console window closes down. suppose i want to make another calculation right away. what can i do to include the funtionality to make another calculation without console window getting closing down.

actually i want the line "The mean is:" to look bold and blue. how can i make it look this way.

i am too much grateful to all of you for teaching me this programming. i am sorry about my english. i am working hard to improve it.

cheers
 

Attachments

  • averge4 running.jpg
    averge4 running.jpg
    7.3 KB · Views: 355
  • #18
painterguy said:
there is no space between "61" and "Press any key to continue...". how can i create space?

To put a horizontal blank space in between, simply have your program output a blank space immediately after the number:

Code:
std::cout << "The mean is: " << (a + b + c + d) / 4 << " ";

You might prefer to have "Press any key..." appear on a separate line. In that case, try the following two versions:

Code:
std::cout << "The mean is: " << (a + b + c + d) / 4 << "\n";

Code:
std::cout << "The mean is: " << (a + b + c + d) / 4 << "\n\n";

("\n" is the "newline" character.)
 
  • #19
painterguy said:
second thing is when i press any key console window closes down. suppose i want to make another calculation right away. what can i do to include the funtionality to make another calculation without console window getting closing down.
Not much you can do about that unless you start up the command prompt manually, go to the directory with the executable and run it. Not that hard, though. Let's say your program's .exe is in a directory called "C:\MyProjects\FirstProgram\Debug" and is called "FirstProgram.exe". These steps should work:

1. Start the command prompt. Go to your Start menu (or whatever they call the menu on the bar with all your programs in it) and there should be an option called "Run..." in there somewhere. Choose that. When prompted for what to run, type "cmd". That should open the command prompt.
2. Type "C:" to go to the right drive if not already there.
3. Type "cd \MyProjects\FirstProgram\Debug"
4. Type in the program executable's name to run it. In this example, type "FirstProgram" (typing in the .exe file extension is not necessary, but won't hurt either).

That should run the program, and when done, you'll be left at the command prompt where you can run it again or do whatever else you want. Obviously, you'll want to know exactly where your real program is located.

painterguy said:
actually i want the line "The mean is:" to look bold and blue. how can i make it look this way.
Not sure how that would be done now. In the old days, we could use "ANSI codes", which I won't get into. Not a clue if that still works. In Unix, we'd use a library like 'curses' or similar. Generally, if I want to make it look fancy, these days, I just make a GUI. I wouldn't recommend jumping right into GUI programming as a beginner, though.
 
  • #20
Grep said:
That should run the program, and when done, you'll be left at the command prompt where you can run it again or do whatever else you want. Obviously, you'll want to know exactly where your real program is located.Not sure how that would be done now. In the old days, we could use "ANSI codes", which I won't get into. Not a clue if that still works. In Unix, we'd use a library like 'curses' or similar.

many thanks jtbell and Grep.

1:-- in order to run it again i think i will require to choose .exe file again?

2:-- will someone help me with that color and bold issue? please

3:-- what can i do that x^2 appear as [tex]x^{2}[/tex]?

For example: This program calculates the real roots of quadratic equation, [tex]ax^{2}+bx+c.[/tex]

i am very much happy with help you provide me. i hope i will learn a lot from you nice people.

4:-- jtbell used character "\n" for new line. i think quotations are part of code. there is another code "endl". what is the difference?

cheers
 
Last edited:
  • #21
painterguy said:
many thanks jtbell and Grep.

1:-- in order to run it again i think i will require to choose .exe file again?
Yes, once the program completes execution, you'll end up back at the command prompt. You can just type the program name again and it will run again.
painterguy said:
2:-- will someone help me with that color and bold issue? please
I checked and ANSI codes haven't been supported for some time, so that won't do it. Looks like there's a platform specific API (will only run on Windows systems). I personally wouldn't bother, but I prefer to write portable code (i.e. that will run on other systems than just Windows). One reason is that if you write Windows only code, I will not be able to run it on my Linux system and won't be able to help.

I doubt very many people use that API, but from what I can gather, you can make a call like this:

SetConsoleTextAttribute(ConOut, background|FOREGROUND_RED|FOREGROUND_INTENSITY);

Here's the API documentation at Microsoft:

http://msdn.microsoft.com/en-us/library/ms682010(v=VS.85).aspx

I believe you only need to #include "windows.h" to have access.

I personally think trying to make a console application output anything than raw text on a Windows system is a waste of time. I'd forget about that until you're ready to learn GUI programming, but of course it's up to you. Perhaps someone else has experience with the Console API and can help further. I don't have a Windows system so I can't test it or experiment with it (I run Linux).
painterguy said:
3:-- what can i do that x^2 appear as [tex]x^{2}[/tex]?

For example: This program calculates the real roots of quadratic equation, [tex]ax^{2}+bx+c.[/tex]
I believe this one should be doable, but I don't think cubed and above is possible (at least without doing some funky stuff). There's a squared character in the DOS character set. Here's the character set in question (which is totally not portable to non-Windows systems either, BTW):

http://en.wikipedia.org/wiki/Code_page_437

This line should print x^2, I think:

std::cout << "x\xB2\n";

Note how I did \x (the backslash as the escape character, and x to signify a hex number follows) then B2 for the hex value of the squared character.

painterguy said:
i am very much happy with help you provide me. i hope i will learn a lot from you nice people.

4:-- jtbell used character "\n" for new line. i think quotations are part of code. there is another code "endl". what is the difference?

Now that is a good question. They both work as a newline, so you won't notice a difference directly. But they are slightly different. Do you know what a buffer is? Output to the console (or file, etc) is generally buffered. When you output characters, they go into a buffer. Once the buffer fills or is flushed, it is output to the actual device (screen, etc). The difference is that \n doesn't flush the stream, whereas std::endl does.

Now, unless you want to flush the output at every line, you want to use \n. If you want to make 100% sure the text will be output after each line without fail, use endl. It's rarely necessary to do so. Can be useful if you use cout for debugging output, since it's buffered. If the program should crash before the buffer is flushed, you won't see some of the text you tried to print. But in that case, I suggest using cerr instead of cout, since cerr is not buffered for exactly this reason.

Hope that clears up the \n vs. endl issue. If not, ask away.
 
  • #22
Grep said:
This line should print x^2, I think:

std::cout << "x\xB2\n";

Note how I did \x (the backslash as the escape character, and x to signify a hex number follows) then B2 for the hex value of the squared character.

hi Grep,

i compiled your code. here is output:-
http://img140.imageshack.us/img140/5426/grepcode.jpg

what is escape character, hex number and hex value? i am sorry i am asking many questions here. hope you will not mind. many thanks for the help.

cheers
 
  • #23
painterguy said:
hi Grep,

i compiled your code. here is output:-
http://img140.imageshack.us/img140/5426/grepcode.jpg

what is escape character, hex number and hex value? i am sorry i am asking many questions here. hope you will not mind. many thanks for the help.

I don't mind questions in the least. It's a pleasure to have someone who wants to learn, and your questions are good ones. So don't worry, ask away.

I wonder if the Windows console now uses UTF-8 characters. I suspect that may be the case now. Does this work?

std::cout << "x\xC2\xB2\n";

If that works, then there's a table of values for it here:

http://www.utf8-chartable.de/

As for the other questions, I'll start with escape characters. Ok, say you're designing a way of specifying a string of characters (like a C++ compiler, input file, etc). So you decide you want to delimit it with double-quote characters (i.e. "). Perfect, now you can do this, and you know where the string starts and ends:

"This is a string."

Now you want the string to be:

This is a quote character: "

So you would encode the string like this:

"This is a quote character: ""

Do you see the problem? It will interpret the first " character as the end of the string. You won't get your quote and any program parsing this will get confused and probably think there's an extra " character that shouldn't be there. So you need a way to tell it that the first quote should be interpreted in a special way. Enter the escape character. It's often (as in C/C++) the backslash character. You would encode it like this:

"This is a quote character: \""

Of course, if you want the string to contain an actual backslash, you need to escape it as well with... another backslash! Like so:

"This is a backslash character: \\"

Which is why newline is \n. You can't type in the newline character in the string, so you use the escape character to tell it that you don't mean the character n, but rather \n which means a newline character. Actually, technically, \n is a linefeed character, which causes a newline in Unix systems. In Windows, the end of line is really \r\n, but the compiler is smart enough to output \r\n (carriage return + line feed) on Windows systems when it sees \n.

As for hex (short for hexadecimal), that has to do with number bases. Normal numbers we're used to are base-10. Binary numbers are base-2, and hex numbers are base-16. Instead of counting "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...", you now have 16 rather than 10 characters to represent a digit. So we add "A, B, C, D, E, F" as digits and we now count like so: "1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, 10, 11, 12, ..."

Here's a wiki page on hexadecimal:

http://en.wikipedia.org/wiki/Hexadecimal

It's handy because one digit in hex corresponds to 4 bits in binary. So 8 bits requires 2 hex digits, and so on. It's easy with a bit of practice to convert binary to hex and vice-versa. For example, converting binary to hex:

0101 1010

0101 is 5 (in both decimal and hex) and 1011 is 10 in decimal or A in hex. So the hex number is just:

5A

It's just as easy to convert back to binary. It's a very useful skill to know, and isn't as hard to learn as one might think at first glance.

Hope that helps!
 
  • #24
Grep, i am very, very much gratefl to you for your help and encouraging words. i will ask questions tomorrow or day after tomorrow. right now just wanted to say thanks.

cheers
 
  • #25
You're quite welcome. :smile:
 
  • #26
My suggestion would be to start with 'C' first. Otherwise when you come across advanced (for now!) topics like dynamic memory allocation, you will not know about POINTERS, which are very very useful. Also when you come across classes and objects you will notice why they are required (because C had structures only). The 'commercial' programming languages are C# and Java. If you want to be a professional I would suggest learning C and then C++.
 
  • #27
Also in the above program, you can replace std::cout with cout.
 
  • #28
RobikShrestha said:
My suggestion would be to start with 'C' first. Otherwise when you come across advanced (for now!) topics like dynamic memory allocation, you will not know about POINTERS, which are very very useful. Also when you come across classes and objects you will notice why they are required (because C had structures only). The 'commercial' programming languages are C# and Java. If you want to be a professional I would suggest learning C and then C++.

thanks RobikShrestha. you are right. first i am not going to be professional. second i am learning this programming thing with some1 else who is learning c++ so i am stick with it. i only need basic understanding of programming and c++. many thanks for your suggestions.

cheers
 

1. What is C++ programming?

C++ is a general-purpose programming language that was developed in the early 1980s by Bjarne Stroustrup. It is an extension of the C programming language and is commonly used for developing system software, application software, device drivers, and video games.

2. What are the basic concepts of C++ programming?

The basic concepts of C++ programming include data types, variables, control structures (such as if/else statements and loops), functions, arrays, and pointers. These concepts are essential for understanding and writing C++ code.

3. How do I write a simple C++ program?

To write a simple C++ program, you will need to first set up a development environment and choose a text editor or integrated development environment (IDE). Next, you will need to write your code using the C++ syntax and compile it using a compiler. Finally, you can run the compiled program to see the output.

4. What are some common mistakes to avoid when learning C++ programming?

Some common mistakes to avoid when learning C++ programming include not understanding the difference between = and ==, not using proper syntax and semicolons, not properly initializing variables, and not properly handling memory allocation and deallocation. It is important to pay attention to details and practice writing clean code to avoid these mistakes.

5. What resources are available for learning C++ programming?

There are many resources available for learning C++ programming, including online tutorials, textbooks, video courses, and coding websites. It is also helpful to join online communities and forums where you can ask questions and get feedback from experienced programmers. Additionally, practicing coding and working on projects is crucial for improving your skills and understanding of C++ programming.

Similar threads

  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
25
Views
2K
  • Programming and Computer Science
Replies
4
Views
3K
  • Programming and Computer Science
2
Replies
40
Views
2K
  • Programming and Computer Science
Replies
6
Views
889
  • Programming and Computer Science
Replies
30
Views
2K
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Programming and Computer Science
3
Replies
73
Views
4K
  • Programming and Computer Science
2
Replies
39
Views
3K
Back
Top