Welcome Guest ( Log In | Register )



2 Pages V   1 2 >  
Reply to this topicStart new topic
> Basic C++ Language, Getting started with C++
mastercomputers
post Jan 3 2005, 04:17 PM
Post #1


BUG.SWAT.PATROL
Group Icon

Group: Members
Posts: 626
Joined: 1-September 04
From: Auckland, New Zealand
Member No.: 27



You will need passion, devotion and even obsession to really appreciate C++ Programming.

Lets grab a compiler

If you have a C++ Compiler then you are all set for turning your C++ code into executable files, if you do not then I recommend getting dev-c++. To learn more about that compiler I recommend browsing their site.

First Program - number.cpp

So now I'm going to write up our first program to learn from, which shows how we can display text to the screen. I know it's probably a bit simple, so maybe I'll spruce it up a bit, as no matter how complex a code can get, the best way to learn is explaining it, so why start off with a simple hello, world when more things can be introduced and explained?


Lets see what I do:

//----------------------------------------------------------------------
// Name: number.cpp
// Description: checks number is greater than or less than zero
//----------------------------------------------------------------------

#include <iostream>

using namespace std;

int main()
{
    [/tab]int number; // defines a variable to store an integer

[tab]cout << "Enter a non-zero integer: ";
    [/tab]cin >> number;

[tab]while(number != 0)
    [/tab]{
[tab]    [/tab]if(number > 0)
[tab]    [/tab]{
[tab]    [/tab][tab]cout << "That integer is greater than zero." << endl;
    [/tab][tab]} // end if statement
    [/tab][tab]else
[tab][/tab]    [/tab]{
[tab]    [/tab][tab]cout << "That integer is less than zero." << endl;
    [/tab][tab]} // end else statement

    [/tab][tab]cout << "Enter a non-zero integer: ";
    [/tab][tab]cin >> number;
[tab][/tab]} // end while loop
    [/tab]cout << "You entered zero." << endl;
[tab]return 0;
} // end main function

I would like to point out that this program has it's flaws. With any code, if we are getting users to input data, we have to check that data and make sure that it's the correct type allowed, if not then our programs may not function how we intended it to be. We will however fix it up, later on.

This program is console based, meaning it's a dos-like program. It's best if ran from the command prompt. Save this program as number.cpp, compile it then open up a command prompt browse to where you compiled the executable and run it. Enter 0 (numeric zero) to exit.

This program demonstrates outputting strings to screen, simple data types, getting user input, while loops, if-else statements and more. Read on to find out what it all does.

So to explain this program we will begin at the very first section.


Comments

CODE
//----------------------------------------------------------------------
// Name: number.cpp
// Description: checks number is greater than or less than zero
//----------------------------------------------------------------------


First of all you need to understand that anything after two forward slashes // comments out the entire line after it, this is the C++ style of comments, you can still use the old C-style of commenting, anything enclosed between /* and ended with */ will be commented.

The only noticable problem with the C-Style way is that the compiler must check everything after /* looking for the ending */ before continuing, the C++ style comment says that anything after the // can be ignored so it moves onto the next line without searching for an ending.

What I've done in this commented section is I am telling people who read this source the name of this file and a brief summary of what it's suppose to do. It's a good idea to use comments within your code to explain sections of the code. Comments are not compiled into a program, it's only their for the viewers benefit.

CODE
// This is the C++ style comment
/*  This is the C-Style comment,
and can span multiple lines */



#include <iostream>

This is our #include preprocessor directive, this inserts the header file iostream into the code at this point. Header files contains many functions and objects, including the cout and cin objects which we will be using later on in our program. We need to declare such headers for these functions and objects in C++ so that our program knows how to use them when it encounters them.

Here are the allowed preproccessing directives in standard C++:

CODE
#define - Defines a token
#elif - The else-if directive
#else - The else directive
#error - Current error
#if - The if directive
#ifdef - The if-defined directive
#ifndef - The if-not-defined directive
#include - Includes a file
#line - Current line
#pragma - Special function run before the rest of the code
#undef - Undefine


Preprocessor directives are handled before the C++ compilation process starts.

Any code that uses cout or cin must include the iostream header.

Header files included in the C++ library were created by others to eliminate recreating the wheel, when it came to writing code. These standard sets of commands were included in the standard template Library (STL).


using namespace std;

This line is added because we're using the new C++ style header file iostream, the names in iostream are part of the namespace std, which stands for standard. The main reason we are using this is to save us from writing:

CODE
std::cout << "This is a string" << std::endl;


Technically you're suppose to prefix certain objects with std::, but by making std the default namespace as we have done, it is assumed that those objects will be using std. This isn't the complete reason for why we're using this, but it is the reason for this program, other reasons would be to avoid conflicts between the names we use in a program and the names other programmers may have used. If you use the same names in different namespaces, there is no conflict. So for example, a function (a set of instructions to be performed, we'll learn more about this later on) written by someone else can't overwrite yours by mistake.


int main() {...insert code here }

This starts our main function. The main function is the point where control is passed to your program from the operating system. What does that mean? This is where you place the code you want executed first. All C++ programs require a main function, with only a few exceptions but we will not get into those yet.

The structure of int main() is followed by curly braces { } enclosing the code that forms the body of the function and that is executed when the function is called. The int keyword in front of main indictates that this function main will return an integer value to the Operating System.

This is how functions work, the code in them is run when the function is called. main is called the program's entry point.



Important tip for what's about to come

To end a simple statement in C++ we must use a semi-colon ; This character pretty much acts like a period at the end of a sentence, while the statements act like the sentences. There's also compound statements, code that would usually be enclosed in curly braces { }, if this is the case, then you should not use a semi-colon at the end of it, examples of compound statements would be creating functions using the function keyword, any of the loop statements and if-else statements.


int number;

int is one of the builtin types. It's called a simple type, after you declare a variable of a simple type, C++ sets aside space for it in memory and you can use it in your program. int is our basic integer type which declares we will be using whole numbers, positive or negative.

After int we have the variable name number, this is the name we refer to in our program, look at it as a placeholder for an integer, number is our declared integer variable, it has been set aside space in our memory and we can use it to store an integer and be able to do all sorts of things to it.

We did not have to call it number though, we could have given it any name we wanted to, the better the name helps you understand what it's for the better it is for you.

Examples:

CODE
int number; // declares a variable to store integer
int anotherNumber = 486; // declares a variable and initialises the number 486;
int a, b, c; // declares multiple integer variables at once.


TIP: When explaining variables, e.g. int number = 500; We should describe it as: 'number' is a container that reserves enough space in memory to store an integer value, we refer to this integer value by using it's given name 'number'. 'number' has been assigned using the assignment operator to store the value '500' inside it.

If you can imagine a box, that has been given a name, the size of the box is determined by what the box is specifically suppose to hold by telling it what items it can hold (data types). Data types do two things for this, size it can hold and type of data it can take.

cout << "Enter a non-zero integer: ";

We display "Enter a non-zero integer: " message using the iostream object named cout. This object cout, handles the text-based output we want to display from a program. We use the << operator here to send the text "Enter a non-zero integer: " to cout. You use operators to perform work on data values called operands. e.g. 4 + 9 uses the plus (+) operator to add the operands 4 and 9.

cout is a special stream object in C++ that can handle many of the details for you. You can pass text or numbers to cout and it'll be able to handle both by itself.

CODE
cout << "Hello, World!"; // prints Hello, World! to stdout (the screen)
cout << number; // prints what is stored in the variable name number




cin >> number;

cin is used for reading text-based input from stdin, most commonly the keyboard, this object is what grabs user input and stores it in the variable we declared earlier on, in this case our integer number,

cin will not return any value until the user presses ENTER, it will only grab the first set of characters up until it reaches a whitespace. whitespace is anything from tab, space, NULL characters. If we tried to input "686 123" and then output it, we would only get 686, the rest would not show, this is because cin encountered a space in the string and therefore did not continue to the end of it. We can grab multiword lines of text but that will be explained in a later time.

So the above simple statement waits for user input, when ENTER is received it stores that input in the variable we declared.

NOTE: What if our user does not input the expected data type? Say our user accidently inputs letters instead of the expected integer/number, then we will have problems and our program may not function how it is suppose to be. That is why at the end of this, I will show you how we can correct this, so that our program will terminate automatically so that it can not malfunction. If you do attempt to try the program without a fix, then you may need to know how to force a break in your program. CTRL + C is your friend.

Notice that the operator >> for cin is pointing opposite direction to the operator used for cout, <<. This is something you will need to remember, once you get comfortable at knowing which operators to use with these objects, you will not have any problems with them. Try and find a way that will help you, maybe think of the way they point or the what the mouth of them are opened at. Just make sure you have them the right way round, your compiler will let you know if you've got them around the wrong way.

while(number != 0) { ... execute statements in here }

A while loop keeps executing the statement in it's body as long as this particular condition is true. In our case the condition is (number != 0) which means. while our variable number is not equal to zero. So if our user entered a number when we asked for it using cin that was not zero, this condition would evaluate to true and whatever is in the curly braces would be executed. Until this condition is false would we ever leave this loop or if for some reason we force the loop to exit prematurely.

So how would we make this condition false, easy, if we entered the number zero, the condition would be if zero is not equal to zero execute the loop, but since zero does infact equal zero, then this condition is false and the loop will not execute, not even once, it will then proceed from the end of the loops last curly braces.

We really need to know more about these Logical and Relational Operators we use in conditions, so I'll explain what they are.

Relational Operators
Less than <
Greater than >
Less than or Equal to <=
Greater than or Equal to >=
Equal to ==
Not Equal to !=

Logical Operators
Logical And &&
Logical Or ||

About Relational Operators

Relational Operators are used to create expressions that evaluate to either true or false, and these expressions are used in conditional statements like the if statement or as a test expression in a loop statement.

The test expression in this case is the while(number != 0), while will continue looping through the code of the curly braces until it's condition is false. The expression that evaluates to either true or false is number. If you wanted to loop infinitely, we could do:

CODE

while(true) { ...execute this code;... }


There's some reasons to why you would use this infinite loop, but at this stage it's best to only use it if you understand what you're doing, as a infinite loop if used incorrectly can give you problems.

So if our expression evaluates to anything other than zero then while will evaluate to true and proceed with the code again, then loop back to evaluate the condition again. If number resulted in some form of error, maybe inputting something other than a number or going outside the bounds of an integer, you'll cause an infinite loop as a result of this. This is why you require data checking.

Still to be continued... sorry for being slow, balancing many things on a plate at the moment, nearly dropped the saucer.

Cheers,


MC
Go to the top of the page
 
+Quote Post
r3d
post Jan 8 2005, 06:43 PM
Post #2


death
Group Icon

Group: Members
Posts: 268
Joined: 8-September 04
Member No.: 384



QUOTE(mastercomputers @ Jan 4 2005, 12:17 AM)
You will need passion, devotion and even obsession to really appreciate C++ Programming.


and also you need lots of resource smile.gif

*move* to tutorials section smile.gif
Go to the top of the page
 
+Quote Post
mastercomputers
post Apr 4 2005, 12:00 PM
Post #3


BUG.SWAT.PATROL
Group Icon

Group: Members
Posts: 626
Joined: 1-September 04
From: Auckland, New Zealand
Member No.: 27



Since I haven't been able to finish the tutorial yet, here's my proposed fix up to the flaw with this program, trying to still keep it basic, but this is an idea, we could continue with the program however, I decided we'll exit it instead of continuing.

CODE
#include <iostream>

using namespace std;

int main(void)
{
int number = 0;

cout << "Enter a non-zero integer: "; //writes string to standard out (monitor/screen)
fflush(stdout); // cleans our standard out buffer
    // use this when endl is not used.
if(!(cin >> number)) // takes in our input from stdin (keyboard) then checks whether
      // it is valid, by checking if it returns true or false.
      // most cases anything that is not a valid integer
      // characters, higher or lower than an int size, etc
{
 cerr << "Error: Invalid Number" << endl; //writes string to our standard error output
            //stderr, which should be used for errors
 exit(0); // exits with zero (zero usually means success, but we can change it to
    // whatever number we want and use it as our error code for debugging
} // end if statement

while(number != 0) //Start of our while-loop, exits on zero
{
 if(number > 0) // checks whether the number is greater than 0
  cout << "That number is greater than zero." << endl;
 else // if our first condition is false, then this will be performed as long as the
   // while condition does not evaluate to true
  cout << "That number is less than zero." << endl;
 
 cout << "Enter a non-zero integer: "; // second request for another number
 fflush(stdout);
 
 if(!(cin >> number))
 {
  cerr << "Error: Invalid Number" << endl;
  exit(0);
 } //end if statement
} //end while loop

cout << "You entered zero, program will now terminate.  Goodbye!" << endl; // zero was entered,
                  // success message

return 0;  // exit program successfully

} // end of main function


I've tried commenting it, and I'm hoping it's self explanatory, hopefully the code box formatting isn't too messy.

Cheers,


MC
Go to the top of the page
 
+Quote Post
the empty calori...
post May 15 2005, 12:53 AM
Post #4


Premium Member
Group Icon

Group: Members
Posts: 254
Joined: 28-December 04
Member No.: 1,884



I keep seeing things for C++..But I would like to learn just plain C.
Go to the top of the page
 
+Quote Post
IcedMetal
post May 23 2005, 01:39 AM
Post #5


Member [ Level 1 ]
Group Icon

Group: Members
Posts: 46
Joined: 23-May 05
Member No.: 5,347



CODE
if(!(cin >> number))

You are using the function cin, bascically the input function, as a variable. You need to do something like this
CODE
cout << "Enter a number";
cin >> number;


Hope that helped.
Go to the top of the page
 
+Quote Post
qwijibow
post May 23 2005, 09:44 AM
Post #6


Way Out Of Control - You need a life :)
Group Icon

Group: Members
Posts: 1,366
Joined: 14-September 04
From: Nottingham England
Member No.: 570



IcedMetal.
In C++ functions can have return values, after these runctions have executed, they pass back a result. The result can then be used asif it was it was in the place of the function.

e.g.
take the function...
CODE

bool PosativeNumber(int n) {
   if n>=0 { return true; }
   else      { return false; }
}


it returns true if the number you pass it as a parameter is a positive number, false if it is a negative.

so in an if block
CODE

if(isPosative(-10)) {
 //do somthing
}
else {
  // do somthing else
}


isPositce will return false, and the else code will run.

in other words.. the computer wil act like the above code was just a plain
CODE

if (false) {


return types can be anything.
Go to the top of the page
 
+Quote Post
IcedMetal
post May 24 2005, 01:25 AM
Post #7


Member [ Level 1 ]
Group Icon

Group: Members
Posts: 46
Joined: 23-May 05
Member No.: 5,347



Heh, sorry 'bout that. I have never done it like that and just looked at it as a syntax error. smile.gif
Go to the top of the page
 
+Quote Post
amit
post Aug 22 2005, 06:16 AM
Post #8


Newbie [ Level 2 ]
Group Icon

Group: Banned
Posts: 29
Joined: 21-August 05
Member No.: 7,994



That was a really good tutorial on C programming..

plz move it to the tutorials..
Go to the top of the page
 
+Quote Post
bedakilla
post Dec 31 2005, 04:27 AM
Post #9


Newbie [ Level 1 ]
Group Icon

Group: Members
Posts: 4
Joined: 31-December 05
Member No.: 10,376



wow thanks man. This really helping me because i just started in my C++ and i was looking around for C++ tutorials and helps. Now instead of going to many website, I can just come here to help smile.gif
Go to the top of the page
 
+Quote Post
mastercomputers
post Jan 7 2006, 12:14 AM
Post #10


BUG.SWAT.PATROL
Group Icon

Group: Members
Posts: 626
Joined: 1-September 04
From: Auckland, New Zealand
Member No.: 27



QUOTE(bedakilla @ Dec 31 2005, 05:27 PM)
wow thanks man. This really helping me because i just started in my C++ and i was looking around for C++ tutorials and helps. Now instead of going to many website, I can just come here to help smile.gif
*



I should really finish this tutorial off, I forgot all about it. (irony is, it's been exactly a year!)

Well, hopefully I'll get something done within the few weeks to complete this, I might even make alterations to it slightly to fix errors I noticed and to make the explanations even more clear.

The reason I never placed it in the tutorials section was mainly because it was work in progress, I can't really sit here for hours on end writing the tutorial till completed, so I had to build it up in parts. It was ok to move to the tutorial section though, it was bound to end up there anyways.


Cheers,


MC
Go to the top of the page
 
+Quote Post

2 Pages V   1 2 >
Reply to this topicStart new topic

Collapse

> Similar Topics

Topics Topics
  1. Basic Tips and Tricks in HTML(15)
  2. Your Most Favourite Computer Language(84)
  3. Basic css code(2)
  4. Visual Basic Help(5)
  5. Online Multiplayer Game(12)
  6. Visual Basic: Replace Explained!(4)
  7. Visual Basic: Random Strings!(10)
  8. VB.NET: Switch Regional Language Automatically(1)
  9. Python Versus Java ?(4)
  10. Does Anyone Code Using Turing(2)
  11. Visual Basic 6 + Crystal Reports 9(6)
  12. Hi Dudes(1)
  13. Where To Start Learning Programming(16)
  14. Hamachi - Your Next Best Friend(2)
  15. C++: Basic Classes(5)
  1. Asterisknow Pbx (voip Telephony)(1)
  2. Phpbb - Installation Tutorial ( For Newbies Based On Astahost Cpane)l(4)
  3. How To Change Language At Login Screen(7)
  4. Poll / Debate: Is Php A Programming Language Or A Scripting Language?(12)
  5. Basic Forensics: Winhex(1)
  6. Lesson1 :introduction To Visual Basic(2)
  7. Increase Your Knowledge Of Html Language(11)
  8. How Do I Get Started?(3)
  9. Some Usefull Linux Basic Commands And Utilities. Please Add To This List If You Know One.(0)
  10. Who Is No. 1 Actor In India (all Language Including Bollywood)?(1)
  11. Linux Basic Command - For Storing Compilation Error To File(1)
  12. Basic Css(4)
  13. An Absolute Basic Guide To Algorithms For Dummies(0)