Basic C++ Language - Getting started with C++

Pages: 1, 2
free web hosting

Read Latest Entries..: (Post #19) by Miles on Mar 27 2008, 07:14 PM. (Line Breaks Removed)
Very good tutorial, I already have experiance in both C and C++, and these tutorials certainly should do better than what I done, that being trial and error and looking at already programmed programs for assitance, I'm glad Umar Shah has decided to expand on this.
Read the FIRST post of this Topic. - Express your Opinion! Contribute Knowledge :-).

Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > C and C++

Basic C++ Language - Getting started with C++

mastercomputers
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

 

 

 


Reply

r3d
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

Reply

mastercomputers
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

 

 

 


Reply

the empty calorie
I keep seeing things for C++..But I would like to learn just plain C.

Reply

IcedMetal
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.

Reply

qwijibow
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.

Reply

IcedMetal
Heh, sorry 'bout that. I have never done it like that and just looked at it as a syntax error. smile.gif

Reply

amit
That was a really good tutorial on C programming..

plz move it to the tutorials..

Reply

bedakilla
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

Reply

mastercomputers
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

Reply

Latest Entries

Miles
Very good tutorial, I already have experiance in both C and C++, and these tutorials certainly should do better than what I done, that being trial and error and looking at already programmed programs for assitance, I'm glad Umar Shah has decided to expand on this.

Reply

Umar Shah
CODE

#include<stdio.h>
void printArr(int arr[]);
int getMultiple(int a, int cool.gif;
int main(int argc, char *argv[])
{
int array[10];
int j;

for(int j=0;j<10;j++)
{
array[j] = getMultiple(j, 3 ) ;
}

printArr(array);
return 0;
}

void printArr(int arr[])
{
int j;
for(j=0;j<10;j++)
{
printf("the %d th value of arr is \n",j,arr[j]);
}

int getMultiple(int a, int cool.gif
{
return a * b;
}
}


in this example the vales are assigned by calling the function getMultiple.
this function returns the product of the arguments passed to it.

Reply

Umar Shah
Next we can try to understand a basic philosophy that everything is done in functions.

lets see how we can use some of the previous examples to understand basics of functions.


CODE

#include<stdio.h>
void printArr(int arr[]);
int main(int argc, char *argv[])
{
int array[10];
int j;

for(int j=0;j<10;j++)
{
array[j] = j * 3;
}

printArr(array);
return 0;
}

void printArr(int arr[])
{
int j;
for(j=0;j<10;j++)
{
printf("the %d th value of arr is \n",j,arr[j]);
}
}


the reult of this program is sam, it assigns and then prints the values of array;

but the function of printing values is carried out by a separate function called printArr which does not return any value but carries out the task of printing the values.

Reply

Umar Shah
Next thing we would want to do is talk about arrays

An array is an ordered list of values.

CODE

#include<stdio.h>
int main(int argc, char *argv[])
{
int arr[10];
int j;

for(int j=0;j<10;j++)
{
arr[j] = j * 3;
}

for(int j=0;j<10;j++)
{
printf("the %d th value of arr is \n",j,arr[j]);
}

return 0;
}



the above example demonstrates initializing an integer array of size 10 with multiples of 3 in the first loop.

the next loop prints these vales in that order in which they were stored.

Next example demonstrates a two dimensional array.


CODE

#include<stdio.h>
int main(int argc, char *argv[])
{
int arr[10][10];
int i,j;
for(i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
arr[i][j] = i * j ;
}
}

for(i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
printf("the arr[%d][%d] has value :%d \n",i,j,arr[i][j]);
}
}

return 0;
}


Reply

Umar Shah
another form of the loop is do while
this can be shown in the following example

CODE

int main(int argc, char argv[])
{

int i=0;
do
{
printf ("Iteration no: %s\n",i);
i = i +1;
}
while(i<10);
return 0;
}



Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Pages: 1, 2
Recent Queries:-
  1. free c tutorial compound if statements video - 36.37 hr back. (1)
  2. phone billing c - 46.37 hr back. (1)
  3. if else while loop in c basic with details description - 55.45 hr back. (1)
  4. basic question asked in c language - 59.96 hr back. (1)
  5. basic c language - 86.32 hr back. (1)
  6. balancing curly bracket using array and link list in c - 92.58 hr back. (1)
  7. example of a program using cin, cout, if and switch statement - 99.50 hr back. (1)
  8. basic of c language with examples - 99.87 hr back. (2)
  9. basic c language programs - 103.39 hr back. (1)
  10. balancing curly bracket using array and link list of c program - 108.47 hr back. (2)
  11. use of loop in c language - 115.27 hr back. (1)
  12. the simple and basic syntax to display a short array of size 10 in c by using cout statement - 116.78 hr back. (1)
  13. basic know about for c language - 128.78 hr back. (1)
  14. c basic for loop - 174.78 hr back. (1)
Similar Topics

Keywords : started


    Looking for basic, c, language, started, c

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for basic, c, language, started, c
advertisement




Basic C++ Language - Getting started with C++



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE