Welcome,fellow,programmers,part,course,which,
Quick Search for:  in language:    
Welcome,fellow,programmers,part,course,which,
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
C/ C++ Stats

 Code: 485,557 lines
 Jobs: 1,067 postings

 
Sponsored by:

 

You are in:

 
Login



Latest Code Ticker for C/ C++.
mini math programs
By Johno on 10/24


The matrix
By Alcodes on 10/24


Palindrome Finder
By Jonathan Volk on 10/24


processor identification and info
By Razvan Petrescu on 10/24


Login Interface using ncurses for Linux
By Suvoraj Biswas on 10/24


Matrix Encryption Algorithm
By Tony Fecteau on 10/23


SMALL TEXT GAME
By cJ! on 10/23


stod
By Mark Jundo P. Documento on 10/23


Basic Loops
By richard james on 10/23


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!





Affiliate Sites



 
 
   

Beginners C++ - Lesson 1

Print
Email
 

Submitted on: 5/15/2000 9:34:38 PM
By: Found on the World Wide Web 
Level: Beginner
User Rating: By 19 Users
Compatibility:C++ (general)

Users have accessed this article 18971 times.
 
 
     Welcome fellow programmers!! This is part one of the course which will show you the basics of programming C++ from scratch using the any platform. If you already know how to use the C++ already, you might want to read later lessons when available. So, lets begin. Found at http://pa.pulze.com/

 

Instructor:   Paul C. Benedict, Jr. (PCC PaulB)
Keyword:    Online Classroom
Resources: PC Development Forum

 

Color coded text:

    black            New things to Remember
    blue             C++ keywords (do, while)
    green           C++ preprocessor directives (#include, #define)


Section 1.1

Welcome fellow programmers!!  This is part one of the course which will show you the basics of programming C++ from scratch using the any platform.  If you already know how to use the C++ already, you might want to read later lessons when available. So, lets begin.

Being developed by mathematicians, C++ is naturally a math-oriented programming language.  It should be very natural since we have all done math to some extent.  The only difficult part is learning the syntax of the C++ language.  Syntax is the use of the language, just like all spoken languages have.  To write a program that works, you must have correct syntax or it will not run.

What the programmer, that's you, write is what is called source code.  Its the source of your program which turns into code, what you run.  What makes this transition is called the "compiler".  The compiler is a program which turns your source into code.  This program is automatically part of programs such as Borland C++ and Microsoft Visual C++.  On a side note, do not get confused with "C++" and "Visual C++" - C++ is a programming language, and Visual C++ is a product which compiles C++.  I get alot of questions about this, so I figured I would clear this up now.

Now lets go more in-depth into making a program.  There are four steps:

    1. Write out your source code (in a .CPP file)
    2. Compile your program
    3. Link your program
    4. Run your program

We have already discussed steps 1 and 2.  Step 3, linking your program is new to us.  You see, there are many programs out there that are already written for you, which means you don't have to write them.  After the compiler compiles your program, it links your program to other pre-written programs, and creates an executable file (.EXE).  This executable file is what is used to run the program.

Now a .cpp file is just like any other text file.  You can write this in notepad if you would, but usually you would use the product's Integrated Development Environment (IDE).  This IDE is "integrated" because it incorporates a text editor, the compiler, the linker, help files, and tools.


 

Section 1.2

In this lesson, we are here to learn the syntax of the C++ language to allow us to delve deeper into the depths of C++ Windows programming in the next lesson.  The most fundamental part of a language are types, variables, and expressions.  The first statement we are going to learn is the assignment expression:

    variable = expression;

For example:

    x = 3 + 5;

This allows us to assign a value of 3 + 5, which is 8 to the variable x.  An expression which is always on the right-side gets evaluated by the compiler and is assigned to a variable on the left.  Please note that expressions can only be on the right side, otherwise the compiler will yell at you "Hey you, what's going on?"  :-)

The = means assign the value of the right to the left hand side.  Remember that you need a variable on the // left hand side of the =, not an expression.  The compiler evaluates the expression on the right hand side, deduces what you mean, and assigns it to the left hand side.  In our example, the compiler evaluates the expression on the right side of the = to mean 8 and assigns it to the variable x on the left side.

The entire line of our example, x = 3 + 5; is called a statement.  If you are a BASIC programmer, you know that you must put everything on one line.  In C and C++, your statement can span multiple lines.  If we wanted, we could write our statement to look like this:

    x = 3
    +
    5
    ;

To the compiler, this makes absolutely no difference.  It sees the statement as the same as if you wrote it on one line (which made it much more readable to us humans) :-)  Please note that for every statement you write, it is ended in a semi-colon ;.  This is very critical, otherwise the compiler will keep on looking at this as one expression and it will look like complete junk to it.  Forgetting the semi-colon is bad syntax, and therefore you are not speaking the language correctly.

It is always required that you declare the type of the variable.  This is because so the compiler knows how much memory to set aside for your variable.  If you do not specify a type, it will automatically be an int.


 

Section 1.3

Now we are going to learn how to do assignments full with variables.  The first thing we must understand about variables are what they are and how to use them in a program.  A variable is a location in your computer's memory where you can save and retrieve information. The type of data can be anything you want.  The most common data we will be using are integers, floating point numbers, characters, and strings.

Integers are numbers like -1, 2, 0, 3456.  Any number that can represented on a number line (remember math?) :-)

Floating point numbers are fractional numbers: 1.0, 3.4, 0.72984, 10E-10.  The reason it is called floating point is because the decimal point can move around through addition.  For instance, .01 * .01 = .0001

Characters are a single letter, number, or symbol.  For instance, 'A', 'B', '3', '@'.  Characters are represented in single quotation marks.

Strings are a collection of characters.  For instance, "How may I help you?",  "This string is filled with junk at the end 232312312312",  "(*&^%".  Strings are denoted by double quotation marks.

Now, here is some code that shows all the types you just learned, except the string.  The string is a little bit more complicated and will be reviewed later:

    int MyNumber = 3;
    float Pi = 3.14;
    char LetterA = 'A';

What we have above is three declarations.  We declare three variables an assign values to them.  We declare the variable "MyNumber" as type "int", which means it is an integer.  We declare the variable "Pi" as type "float", which means it is a floating point number.  We also declare the variable "LetterA" as type "char", which means it is a character.

With numerical data types (like int and float), we can perform simple math operations on them:

    Addition                                    +
    Subtraction                                -
    Multiplication                             *
    Division                                     /
    Modular Division (Remainder)     %

We will not review the four simple math operations, but here is an example of the four:

    int MyNumber = 3;
    MyNumber = MyNumber + 2;
    MyNumber = MyNumber - 1;
    MyNumber = MyNumber * 3;
    MyNumber = MyNumber / 2;

In the first statement, the variable MyNumber is taken, adds 2 to it, and stores it back in MyNumber.  Right now, MyNumber now equals 5.  Then we subtract one and store back the result, multiply by three and store back the result, and then divide by 2 and store back the result.  MyNumber now contains 6.

Please note that the "=" (equal operator) does not mean "equal".  Read it as "assigns".  This assigns the value of the right side to the variable on the left side.

The Modular Division operator (or Remainder operator), returns the remainder of a division:

    int Remainder = 7 % 4;

The variable Remainder contains the value of 3 now.  How did we get that?  Because 4 goes into 7 one time with a remainder of 3.  Please note that the "%" operator always returns an integer value.


Section 1.4

Unlike pure mathematics (the kind of math we do at school), we do not have an infinite amount of memory to store some numbers.  Therefore, computer scientists came up with ways to store numbers in finite quantities.  The date type int, float, and char are all different sizes - and determining which type you use, you must set aside that number of bytes to hold it.  You can use the sizeof operator to find out how much memory (in bytes) a type or variable holds in code - example: sizeof(int).  In the three most commonly used data types we are examining, these are the values:

    sizeof(int)      = 4
    sizeof(float)    = 4
    sizeof(char)   = 1

On a side note, if you were running sizeof(int) on a 16-bit compiler (ones made before Windows 95), it would return 2.  Notice how sizeof(float) and sizeof(int) return the same size (each occupy four bytes in memory), but the memory is used much differently.  It is all dependent on the data type used.

Now, you are probably wondering, what on earth is a byte?  Well, a byte consists of eight bits of information.  As we unwrap this enigma of words, a bit is the SMALLEST piece of information that the computer can work with.  A bit can only be in the ON or OFF position, like your computer.  This on/off system is called the binary system because there are only two numbers in the system (unlike our decimal system which contains ten).  We like to represent on as a 1 and off as a 0.  And if we link a bunch of 1's and 0's together, we get a number the computer can use.  Let's see exactly how the computer does this so we can understand the use of numbers in computers better:

We want to see how the number 8 is represented in computers.  First off, 8 exists in our decimal system (power of tens) and we must represent it in the binary system (power of twos).  This is how the number 8 looks like when broken down into the power of tens:

    10^0 * 8

Above says take 10 to the power (^) of zero, which is 1 and multiply it by 8.  Hence we get the number eight.  In the binary system, this is how it would look:

    (2^3 * 1) + (2^2 * 0) + (2^1 * 0) + (2^0 * 0)

Wow!  That's alot of writing.  Let's examine what is going on:
2 to the 3rd power times 1 is eight.  We add that to 2 to the 2nd power times 0, which is zero.  We add that to 2 to the 1st power times 0, which is zero.  Finally, we add that to 2 to the 0 power times 0, which is zero.  Through all that, we get the answer of 8.

Now, if we look at the multiplication in that binary example, you can see we get 01000.  01000 equals 8 in decimal.  You might be wondering why I took it upon myself to put an extra zero in the front of the binary number.  The reason we do that is because the LEFT most side of a binary number determines if the number is positive or negative.  Remember computers can't use all the fancy math symbols we do, so we have to have some way of making a number negative - this is our way.  Since eight is a positive number, we make the left-most bit a zero.


Section 1.5

Now what the next thing we are going to learn is binary addition and subtraction.  You might be sitting there wondering why we are doing this.  The reason is because as you get more experienced in programming, most of the time you will be dealing with bits of a number, and not the number itself.  This is crucial.

Let's say we are working with a byte and wanted to add the numbers 8 and 5 together.  This is how it would be done:

 

Example 1


    00001000       = 8
    00000101       = 5nbsp; = 5    ----------------------------
    00001101       = 13

Like normal math, we add from right to left:
1.  The right-most column is 0 + 1 which equals 1
2.  Then 0 + 0 equals 0.
3.  Next 0 + 1 gives another 1.
4.  And next 1 + 0 gives another 1.

As you can see, it's pretty basic.  Now let's look at a more complex example.

 

Example 2


    00000001       =  1
    00001111       = 15
    ----------------------------
    00010000       = 16

Hey now, this looks very different.  Let's examine what is going on.
1. When we add 1 and 1 together, we get 2 which is "10" in binary.  So what we do is bring down the zero and carry the one (just like good ol' math).
2. Next we have 0 + 1 + the carried 1.  That yields two again.  So we drop the zero and carry the one.
3. We continue this until the end.


Section 1.6

We must learn how to convert decimal into binary efficiently.  The rules are very simple:
1) Take your number and divide by 2
2) Take the remainder and write it down
3) Take the quotient and make that the number to divide for the next time
4) Repeat step 1 through 3 until the number reaches 0
5) Reverse the list of all your remainders and you have the number in binary

 

Example 3


    Convert decimal 16 to binary
    16 / 2 = 8, remainder 0
    8 / 2   = 4, remainder 0
    4 / 2   = 2, remainder 0
    2 /2    = 1, remainder 0
    1 / 2   = 0, remainder 1

Now look at the remainder list.  We have 00001.  Obviously, that is the number 1 in decimal, so like step 5 says, reverse the list and we get 10000.  Make sure you had that front zero to keep the number positive, so it is really 010000.

 

Example 4


    Convert decimal 11 to binary
    11 / 2 = 5, remainder 1
    5 / 2   = 2, remainder 1
    2 / 2   = 1, remainder 0
    1 / 2   = 0, remainder 1

Now we have 1101.  Reverse it and add the front zero to keep the number positive:  01011

 

Section 1.7

Next up is binary subtraction.  If you remember division in math, there is no such thing.  You would invert the second factor and multiply across.  4 divided by 2, is really 4 multiplied by 1/2, which equals 2.  In binary subtraction, this parallels to what we want to do.  Take the second number and invert all the bits (turning all the zeros to ones and all the ones to zeros) and then add one.  This process of inverting and adding one is called twos complement.

First to understand complementing, let's look at an example:

 

Example 5

    00000101 = 5

Here is the number five in binary.  Now to find out the complement of the number, invert all the bits which makes the number "11010" and then add one:

    11111010   = 5 inverted
    00000001   = 1
    -----------------------
    11111011   = -5

Hey now!!!  It turns out that two's complement gives us the negative version of our number, and to prove it, if we add 5 and our -5 together, we should get zero:

    11111011   = -5
    00000101   =  5
    -----------------------
    00000000   = 0

We get zero!!  If you noticed, we do not extend the number of bits when this is done.  Since we have a finite number of bits to work with and there is an overflow (an extra bit), we just discard it.  Now with this knowledge, to subtract two numbers: Take the first number and add it from the two's complement of the other number.


Section 1.8

Now we are going to look at adding, subtracting, positive, and negative numbers more in-depth.  There are two type of integers: signed and unsigned.  A signed integer means that the number can be either a negative or a positive.  An unsigned integer means that the number can only be zero or positive.  Unsigned integers are useful in absolute situations: the number of apples you have, how much a stamp costs, etc.  This is how you can specify the type:

    signed int i = -100;
    unsigned int j = 40;

Now, if you don't specify the type of integer, it is automatically a signed integer.

Now, we learned that that we used the left-most bit in determining if the number is negative or not.  This is ONLY the case when we work with signed numbers.  When the number is unsigned, the left-bit is just part of the number. In the case of the byte, these are the ranges of a byte:

    SIGNED      = -128 to 127    (uses bits 0 through 6)
    UNSIGNED = 0 to 255         (uses bits 0 through 7)

I hope you enjoyed the first of lessons in learning how to programming C++ from ground-zero.  There is alot of material to be covered, so pay attention, practice, and review.


Keywords and Terms to Remember

Assign
Binary
Bit
Byte

char

Compiler
Expression

float

Floating point
IDE

int

Linker
Modular
Signed

sizeof

Source
Statement
Type
Twos complement
Unsigned
Variable


Summary

The four steps in making a program is: writing code, compiling, linking, and then running your program.

What makes up a language is: types, variables, and expressions.

Correct syntax is needed like any other human spoken language.

int allows integer data types, float creates real numbers with fractional portions, and char stores characters.

The five main math operators are: plus, minus, multiplication, division, and modular division (remainder).

The sizeof keyword returns the number of bytes a type or variable occupies.

The binary system is used in computers to represent numbers.

Binary subtraction is the same as addition just with twos complement.


Other 2 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
5/16/2000 4:10:16 AM:ecko
thankyou for your tutorials on c i have been programming in BASIC for 2 years now and now just getting started with c this helped me alot
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/7/2000 2:26:03 PM:preeti
Thank you for a simple, easy to understand approach for a novice in programming.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/19/2000 4:24:41 PM:Eric Malamisura
A question with how you do your binary numbering is incorrect...There are NO negative numbers in a binary system they are of non-existence..I learned this going through a Cisco course and a programming course in college. In your example you use 11111011as being a -5? Well the way the binary number system works is the power of 2's to the power of... 11111011 represents the number 251 in decimal format..I dont understand what your trying to explain defeats the whole binary system. To get a negative number from binary from my understanding the computer comes up with two number subracts the least number from the greater number to get the negative number... example: 40 - 45 = -5 101000 - 101101 = -5 as you can see the binary numbers themselves dont represent negative numbers but represent whole numbers which in turn represent negative numbers..Could you explain it a bit more in define
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/6/2001 1:31:42 AM:Moltar9000
Thank-you so much dude. I understand this material so much better now.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/25/2001 1:08:24 AM:kain
he is explaining binary wrong !!!!!!!!!!!! take this down before more people see it
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/16/2001 2:02:12 AM:HakNu
I have no idea WTF u r talken about
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/23/2001 8:36:24 PM:Programmer
Pretty good. I to programmed in Visual Basic for about 2 years before switching to C++, and this helped.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/23/2001 6:16:09 AM:Haroldscib@aol.com
thankyou very much for the kind tutorial that has been extremley helpfull well done guys if only every teaching aid was that easy to understand thanks again keep the good work comming regards hazza
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/30/2001 12:02:42 AM:Richard
For a self-teaching person, such as I, this material is really invaluable. I feel very grateful for the effort the author made in preparing this enlightening tutorial. Thank you.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/15/2001 4:51:59 PM:The Wedgie
Regarding the following: Quote: 11111011 represents the number 251 in decimal format This is both true and false, depending on how the number is being treated. For an unsigned integer, this is certainly the case, but the author is talking about signed integers, in which case his representation of the number -5 is perfectly correct. The two's complement can be worked out as follows: Take the number 00000101 (decimal 5) Reverse all the bits 11111010 Add one 11111011 (-5) Which is what the author was saying, HTH
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/19/2002 10:08:49 AM:redjag
How can I set the decimal point of a float? I want it to print out as 500.00 not just 500. I initialized it to 0.00 but this still did not display the decimal points. This tutorial is very helpful and explanatory but couldn't find anything referencing the output to the screen. Thanks
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/9/2002 3:27:17 AM:Oleg Maximovich
Like 'ecko', I've been programming with Basic. This code has a lot of useful information. I bought 2 books, but there is more harder written.... very good.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/20/2002 10:38:45 AM:Neogreg
Thanks from a newbie. This really helps and gets me going in the right direction!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/16/2002 8:27:59 AM:Punk
its not that he is explaining it wrong, its just that he is telling u wrong... no there is not any negative numbers in bianry but what he is actually saying is that 11111011 is the opposite of 00000101...just read it all carefully again and thx alot for the tutorial it helped alot.. Punk
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/20/2002 8:18:03 AM:memerick
thank you very much for the lession. this is my first day of learning this. my girlfriend is taking this class and having troubles with it. I hope to learn in one week what she has learned in five weeks of class. It is all logical.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/1/2002 6:05:06 AM:Unable to run !
Hello.. Whenever I wright down a program and click COMPILE this message appears: ...unable to run program file. What is the matter? For your information, I'm an absolute beginner. Regards
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | C/ C++ Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.