Jump to content
xisto Community
Sign in to follow this  
iGuest

Basic C++ Language Getting started with C++

Recommended Posts

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()

{

int number; // defines a variable to store an integer

 

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

cin >> number;

 

while(number != 0)

{

if(number > 0)

{

cout << "That integer is greater than zero." << endl;

} // end if statement

else

{

cout << "That integer is less than zero." << endl;

} // end else statement

 

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

cin >> number;

} // end while loop

cout << "You entered zero." << endl;

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

 

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

 

// 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++:

 

#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:

 

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:

 

int number; // declares a variable to store integerint 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.

 

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:

 

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

Share this post


Link to post
Share on other sites

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.

#include <iostream>using namespace std;int main(void){[tab][/tab]int number = 0;[tab][/tab][tab][/tab]cout << "Enter a non-zero integer: ";[tab][/tab]//writes string to standard out (monitor/screen)[tab][/tab]fflush(stdout);[tab][/tab]// cleans our standard out buffer   [tab][/tab] // use this when endl is not used.[tab][/tab]if(!(cin >> number))[tab][/tab]// takes in our input from stdin (keyboard) then checks whether     [tab][/tab] // it is valid, by checking if it returns true or false.     [tab][/tab] // most cases anything that is not a valid integer     [tab][/tab] // characters, higher or lower than an int size, etc[tab][/tab]{  cerr << "Error: Invalid Number" << endl;[tab][/tab]//writes string to our standard error output           [tab][/tab] //stderr, which should be used for errors  exit(0);[tab][/tab]// exits with zero (zero usually means success, but we can change it to   [tab][/tab] // whatever number we want and use it as our error code for debugging[tab][/tab]}[tab][/tab]// end if statement[tab][/tab][tab][/tab]while(number != 0)[tab][/tab]//Start of our while-loop, exits on zero[tab][/tab]{  if(number > 0)[tab][/tab]// checks whether the number is greater than 0 [tab][/tab] cout << "That number is greater than zero." << endl;  else[tab][/tab]// if our first condition is false, then this will be performed as long as the    // while condition does not evaluate to true [tab][/tab] cout << "That number is less than zero." << endl;    cout << "Enter a non-zero integer: ";[tab][/tab]// second request for another number  fflush(stdout);    if(!(cin >> number))  { [tab][/tab] cerr << "Error: Invalid Number" << endl; [tab][/tab] exit(0);  } //end if statement[tab][/tab]} //end while loopcout << "You entered zero, program will now terminate.  Goodbye!" << endl;[tab][/tab]// zero was entered,                 [tab][/tab] // success messagereturn 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

Share this post


Link to post
Share on other sites
if(!(cin >> number))
You are using the function cin, bascically the input function, as a variable. You need to do something like this
cout << "Enter a number";cin >> number;

Hope that helped.

Share this post


Link to post
Share on other sites

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

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
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
if (false) {

return types can be anything.

Share this post


Link to post
Share on other sites

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 :D

1064334389[/snapback]


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

Share this post


Link to post
Share on other sites

help in c++

Basic C++ Language

 

Hello mr

 

Iam ali atwi student in master 2 physics in university du maine france , I want help in c++

 

I want a function to generate 0 1st time ( that I used in other function ) then when we generate this function again it give me 1 and so on (0 and 1 ... 0 and 1)

 

it look like ran2() function that genrate a random variable betwwen 0 and 1 when I generate a function it give me a value betwwen 0 and 1 and after I genrate the function next time it give me other random varibale betwwen 0 and 1 which is different from the 1st one.

 

So I want a function look like that that genrate 0 then 1 then 0 and so on

 

Thank you for your time and your help

 

Ali atwi

 

-reply by ALI ATWi

Share this post


Link to post
Share on other sites

This is really an easy task to accomplish, if you know mathematics, when to get this result you only need to get 0 or 1, so for example we get 0 when the number is even or the other way around and we get 1 when it's odd or the other way around, this could be done in a loop or any other way by using modulus %, just read about it what it does, on some other languages it's just mod, for example:

// Even_odd.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){	for (int i=0; i<20; i++)		cout << i%2 << ",";	cout << "\n\n";	return 0;}

The result will be something like this: 0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,

Hope this helped :)

Share this post


Link to post
Share on other sites

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


Learning C should be precondition to all programming.
Anyway What you wnat to learn?

to Start with we can write a simple hello world program.

#include<stdio.h>int main(int argc, char * argv[]){printf("Hello World!\n");return 0;}

the above example just prints "Hello World!" on the screen.
"\n" represents a newline character that makes the cursor go to the begining of the next line.

the return 0 signals the OS that the program ended normally.


#include<stdio.h>int main(int argc, char * argv[]){int i;i=10;printf("The value of i is %d\n",i);return 0;}

the next example just prints "10" on the screen.
"\n" represents a newline character that makes the cursor go to the begining of the next line.

again the return 0 signals the OS that the program ended normally.

Share this post


Link to post
Share on other sites

Now that we uinderstood how to print a number and a string we should next try to understand how to control the flow of a program with the if construct.

#include<stdio.h>int main(int argc, char * argv[]){int i=10;if(i<10){printf("the value is less than 10!\n");}else if(i==10){printf("the value is exactly 10!\n");}else{printf("the value is greater than 10!\n");}return 0;}

the above example will prints "the value is exactly 10!" on the screen.
since the condition i=10 is true, the other printfs wont be called.


Suppose we know a value will take some fixed set of values then we can use switch case as follows:

#include<stdio.h>int main(int argc, char * argv[]){int i;i=10;switch (i){case 1:printf("The value is one\n"); break;case 2:printf("The value is two\n"); case 3:break;printf("The value is three\n"); break;default:printf("The value is not one two or three\n"); break;}return 0;}

Now in the above example the control of the flow is determined by the value of i that switch interprets.
If the value is 1, 2, or 3 the appropriate printf is called.
if none matches then the flow will pass to default and that printf is called.

if we want to group some values then we can do that by omitting the break statements as:

....case 5:case 6:case 7:printf("The value is five six or seven\n"); break;....

Share this post


Link to post
Share on other sites

Now that we know about if we can start to see how a loop works.to begin , we shall start with a while loop.

int main(int argc, char argv[]){int i=0;while(i<10){printf ("Iteration no: %s\n",i);i = i +1;}return 0;}

the above program starts off with a variable i =0.it loops through while construct and prints Iteration no: value_of_ifor each iteration.i = i + 1;increments value of i by 1 ;this can also achieved by

i++;

or also by

i+=1;

while(i<10) is true untill i gets value of 10 and then the program control passes to the line immedately following the closing brace of while.this can also be achieved by a for loop as

int main(int argc, char argv[]){int i=0;for(i=0;i<10;i++){printf ("Iteration no: %s\n",i);}return 0;}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.