Jump to content
Science Forums

Finally learning C++!


Recommended Posts

Been around programmers for years, yet never actually got to work with them. Yes, I don't know one bit about computer programming. I've always wanted to know how to write programs, but I've never had the guts to go on the apparently difficult and gruelling path to become a programmer.

 

Things turned dark and cold when I got to Half-Life map editing. I knew how to make wonderful environments, and got to explore world I created. But the world were horribly empty, or simple repeats of the same things I had created only days back.:snow: I had the source code right under my nose, but didn't have one bit of knowledge about how to use the wonderful tools.:)

 

But now, everything's gonna change. After coming to my new college, I was introduced to a course 'EC-101A'. Instantly I knew that I was where I always wanted to be. I would get to learn C++ in my very first semester, and possibly java by the second...:D

 

So here I am, setting up my base camp, ready to build my bones. I hope others like me will join me in my quest, and those who already have undergone it will assist...

 

I begin tomorrow...

 

Till then, the compiler I use will be 'Dev-C++ 4.9.9.2', available from here.

Link to comment
Share on other sites

lol it needs to be PHP, CF is a hogg and there is really no advantage of using it over PHP anymore :)

 

if you wanna forward me the CF code, i can most definitely find time to start looking into changing it to PHP...

 

Granted that i dont know CF, but then again, that didnt stop me this morning from learning VBScript...

 

Rod, you'll pick it up, its a weird language to learn, but trust me unless you go assembly, after you know C++ you will have no problems learning new languages. And after you know a few, a new language is a matter of reading a book, and 2 weeks later you are programming in that language almost as well as a guy who has been learning it for 3-4 years. Trust me, been there with Python, Perl, Bash, Boe-Bot basic just to name a few....

Link to comment
Share on other sites

Thankyouthankyou! I've had my first class today, and it focusses on the 'preliminaries'. What's a computer? A thingy that performs function on the data you feed it. Duh, big deal.:hihi:

 

We begin from the 'Von neumann computer architecture', which basically refers to there being the instructions and processing unit being two connected, yet somewhat separate entities. Fine... well... that's not new.

 

Next we go to how a instruction is there. It's sorta like 'Operation to be done(What to operate upon)' Such as 'Add (X) and (Y)'. Read(X).

Fine. Cool. What kind of operators are there? To name a few...

 

Arithmetic operators - Add, Subtract, Multiply etc.

Logical 'operators' - Compare: =, <, >, etc.

Jump operators - Stop, Jump over, etc.

Memory operators - Load, Store...

I/O (For input/output) - Read, Display, Print, Beep, etc.

 

And all of there operators are recognised by the computer as (the usual) strings of zeros and ones.

 

Next, came the levels of languages.

We found out about-

Machine level (the zeros and ones)

Assembly level

High level

 

If we dare to code in anything but machine level (which is boring, stupid, and difficult) we have to convert the instructions (in the higher level language) to their machine level counterparts.;)

The program or algorithm (whatever) that we employ to do this (dirty work) is either a 'compiler' or a 'interpreter'. Both are 'translators'. The difference is that a compiler makes the machine level code, and totally saves it so that you can execute whenever. The interpreter reads the high level language 'instructiuon#1', 'interprets' it, executes it then goes to 'instruction#2'. The latter is slower for general purpose usage, but it's for the time when you wanna just try your high level code out and stuff.

 

An example of a high level program follows...

 

 
(A, B are numbers stored in the secondary memory i.e. hard disk, or are simply input)

1   Read 'A'
2   Read 'B'
3   Load 'A'
4   Add 'B'
5   Store 'C'  (whatever you just added)
6   Display 'C'
7   Beep
8   Stop

Hurray. If there was a compiler that could convert these instruction to machine level, I would already have become a programmer...:)

 

Note the numbers before the instructions. They represent the 'address' of the instruction. The location in the memory. Where to find the instruction.

 

Gotte re-hydrate my brain...:beer-fresh:will carry on later.

 

BTW, comments and observations, and hopefully additions on what I give here are totally welcome and requested for!

Link to comment
Share on other sites

'=' doesn't seem to me to be a logical operator to compare, but '==' is.

Just in case you don't know = is an assignment operator a code like

if(x=2)

would not give the desired result. Actually I don't know if it gives a compiler error or always true but I tend more to the error since there is nothing to compare...

 

on the other side the code

int x = 2;
if(x==2)

would give TRUE

and

int x = 3;
if(x==2)

would give false ...

 

Note that in the two preceeding code segments '=' assigned a value to the integer x and '==' checked if the things on its sides are equal...

Link to comment
Share on other sites

Now I have the pleasure of actually writing in C++ language.

 

Here's what I was provided.

 

 
#include <iostream>

using namespace std;

int main ()

{
cout << "Output text";
return 0;
}

It's supposedly the simplest program. Well, that's fun considering I ddidn't make head or tail of half of it at beginning. It's supposed to print 'Output text' on the screen, or whatever default output device in the machine.

 

Before I go on to what I learnt about the code, some things about C++:

  • C++ is a 'freefom' language, meaning that we may write the program in anyway, as long as the instructions are properly formulated and differentiated from each other. Instuctions for the compiler have to end with a ';' We could write a whole program in one single line, or split it up as we want.
  • The language is totally case sensitive. int is different from Int or iNt.
  • The 'white spaces' (i.e. tabs, spaces, enters, blank lines etc) are to be ignored by the compilers. They are there to make the code easier to understand and edit.

Having said that the above code should be the same as:

[font=Verdana][color=black]#include <iostream>[/color][/font]
[color=black][font=Verdana]using namespace std; int main () {cout << "Output text"; return 0;}[/font][/color]

 

or

 

 
#include <iostream>

using namespace std;

   int main ()

{

  cout << "Output text";

return 0; }

 

The lines beginning with '#' are 'preprocessor directives', and are out of this rule.

 

The preprocessor is a program that works just before the compiler, and it's function is to search for directives for it. (It looks for lines beginning with '#") It processes these lines, and adds instructions into the code that we, the humans would find irritatingly boring and repeating (such as input, output methods). The codes it normally is used to adding is what makes C++ a mid-level language. (Needs some checking, is this correct?)

 

Now let's dissect the above program to see it's guts before actually compile it.

 

  • #include <iostream>- A preprocessor directive. Notifies the preprocessor to include the contents of the header file named 'iostream'. I found this file in the dev C++ compiler file folder. It contained this code, which I assume it includes into my code.

 
// Copyright (C) 1997-1999, 2000 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING.  If not, write to the Free
// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
// As a special exception, you may use this file as part of a free software
// library without restriction.  Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License.  This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.
#ifndef _BACKWARD_IOSTREAM_H
#define _BACKWARD_IOSTREAM_H 1
#include "backward_warning.h"
#include <iostream>
using std::iostream;
using std::ostream;
using std::istream;
using std::ios;
using std::streambuf;
using std::cout;
using std::cin;
using std::cerr;
using std::clog;
#ifdef _GLIBCXX_USE_WCHAR_T
using std::wcout;
using std::wcin;
using std::wcerr;
using std::wclog;
#endif
using std::ws;
using std::endl;
using std::ends;
using std::flush;
#endif
// Local Variables:
// mode:C++
// End:

  • using namespace std; - Judging by the ';' at the end, it's an instruction for the compiler, but I have no idea what the hell it is. Help needed!
  • int main () {... body ...} - This is a C++ function, and it works upon the argument contained inside the curly brackets. The 'main' function used here is where all the C++ start their execution. It's the most important function, and must be present in just about all C++ programs. The instructions inside it will be the first to be acted upon.
    • cout << "Output text"; - This is a C++ 'statement' (A 'statement' is an expression that actually produces some effect.) The 'cout' bit is declared in the iostream file (within the std namespace), and represents that what follows has to be sent to the standard output stream (the monitor, here). Again, note that the statement ends with a ';', signifing it's end.
    • return 0; - Says that the main function has ended, and successfully so. (The zero after the end means most of this, actually) This is pretty much the usual way to end a C++ program.

Now lets compile the program! I do so in a few moments...

Link to comment
Share on other sites

Here it is, then. A massive ~450KB file that instantly opens a window, displays the text and closes the window before I can actually read a thing. To read the text, I'm forced to open the program in the command prompt.

 

I'm forced to compress the freaking file. Why is it so big? And why does it close the window the moment it finishes?

 

Again, compiled in the standard dev C++ 5 (beta) environment...

Link to comment
Share on other sites

Here it is, then. A massive ~450KB file that instantly opens a window, displays the text and closes the window before I can actually read a thing. To read the text, I'm forced to open the program in the command prompt.

 

You'll be working for Microsoft in no time. :hihi:

Link to comment
Share on other sites

Been around programmers for years, yet never actually got to work with them. Yes, I don't know one bit about computer programming. I've always wanted to know how to write programs, but I've never had the guts to go on the apparently difficult and gruelling path to become a programmer.

 

Things turned dark and cold when I got to Half-Life map editing. I knew how to make wonderful environments, and got to explore world I created. But the world were horribly empty, or simple repeats of the same things I had created only days back.:hyper: I had the source code right under my nose, but didn't have one bit of knowledge about how to use the wonderful tools.:turtle:

 

But now, everything's gonna change. After coming to my new college, I was introduced to a course 'EC-101A'. Instantly I knew that I was where I always wanted to be. I would get to learn C++ in my very first semester, and possibly java by the second...:turtle:

 

So here I am, setting up my base camp, ready to build my bones. I hope others like me will join me in my quest, and those who already have undergone it will assist...

 

I begin tomorrow...

 

Till then, the compiler I use will be 'Dev-C++ 4.9.9.2', available from here.

 

Congrats, Ronthepon. Although I want to caution that though you feel like you know where you want to be, it'll take actually being there to confirm this! :hyper: That's how I felt when I came to my university and started microbiology...and I'd like to move on to other things in my life, though a part of my heart will never leave the subject.

 

I like Dev-C++ quite a bit; it's a pretty good compiler. I plan on using it to learn and program in C++, although there's a chance I could pick up Visual Studio. Like you, I'm interested in doing programming although this is to see if I can make something of a career of it down the line. I'll also be teaching myself how to write and trying to write fiction in the meantime (this'll actually be my primary focus, to later couple with programming and game design once I feel I know those well).

 

What C++ textbook are you using by chance? I've had this one for a while:

 

Object-Oriented Programming in C++

Amazon.com: Object-Oriented Programming in C++ (4th Edition): Books: Robert Lafore http://www.amazon.com/Object-Oriented-Programming-C%2B%2B-Robert-Lafore/dp/0672323087/ref=pd_bbs_sr_1/002-9832606-8897623?ie=UTF8&s=books&qid=1187558096&sr=8-1

 

Well written and easy to understand, even for the math-averse like me.

Link to comment
Share on other sites

Ronthepon, your question about namespaces.

Generally a namespace is used to prevent conflicts with multiple definitions. Imagine you define a function with the same name of one which is built in C++ (for example rand()...), so you would have a problem.

The keyword using means that you make "visible" all the things defined in the namespace following it. Eventually std is the standard library of C++ where things like cout, cin, etc. are defined. If you would write a program without the using namespace std; comand you would need to specify always when you want to write something to the screen where to take the function cout from, this would be done in the following way:

std::cout<< "hello world"<<endl;

while if you write in the beginning using namespace std; you can print the same thing by typing

cout<<"hello world"<<endl;

since the keyword using makes all definition of std visible.

Link to comment
Share on other sites

ronthepon, if you want to hot have the window close, you have to enter a pause statement:

system("PAUSE");

right before the return statement, it makes you have to hit a key before you exit the program, so you can review the final results or whatever.

 

BTW rod, please dont use namespace std, unless you are using everything in the namespace you dont need to use it, it takes up memory, and in programming terms, needlessly taking up memory = inefficiency.

 

if you are using cout cin ifstream ofstream or whatever you need to use for you program, you can import iostream and then define your std by :

#include<iostream>
using std::cout;
using std::cin;
...

 

note on include, if you are using a microsoft compiler, you may have to have a .h at the end of iostream, because since "microsoft standard compliance" is an oxymoron, you may or may not have to do so (it will error out on <iostream> or your first operation that uses it like cin or cout or something, and that's how you know to use <iostream.h>)

Link to comment
Share on other sites

Ah, finally some free time. I've gone a bit ahead in my course, and I've come across some more things.

 

Thanks, for telling me about namespaces, sanctus, and about the system ("pause") thing, alexander. And yeah, I'll just stick to the std:: thing from now on.

 

BTW, I don't quite have to use the '.h' after the name of the header file(?), the error comes in compiling when I do include the '.h'. But I suppose that's about the compilers.

 

maikeru, I'm gonna buy 'C++ how to program' by 'Dietel and Dietel' pretty soon, or nick it from my library. But till I get my hands on a copy, my lecture notes shall pretty much be my only routes.

Link to comment
Share on other sites

Then, about working with variables.

 

Variables are declared in C++ in a sorta format:

The kind of variable Name of the variable;

 

As an example, if we want to create a variable 'x' which works with only integers, we write:

 

[color=black]int x;[/color]

 

So from now on, we can perform various arithmetic (or other) functions with the variable x in C++. Let’s have some fun!

 

 
A dumb code:

#include <iostream>

int main()
{
 int x;

 x = 2 + 3;

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

 system ("pause");

 return 0;
}

 

 

What the above program does is:

  • Declare a variable 'x' which will take only integral values (and that too, within a particular range).
  • Assign a value of 2+3 to x
  • display the value of x and changes the line (meant by the "n" bit)
  • system ("pause") gives a 'Press a key to continue...' thingy.
  • End program.

Not particularly useful, but nevertheless we actually got the machine to do something.

 

We declared the name o the variable as 'x', and could use any other name as long as we stuck to a few limits for the naming. Here are the rules for the naming.

  • Thou shall use only (a-z) lower case, (A-Z) upper case, (0-9) ten decimal digits, and the (_) underscore.
  • Thou shall not dare to bespoil the reserved words by using them as indentifiers. (Reserved words are basically parts if the C++ syntax, sich as the int, main, if, etc, etc, etc.)
  • Thou shall never use a digit as the first part of your variable identifier. If thee does so, C++ wont regard it as an identifier.

Simple enough to remember.

 

BTW, before we go on having fun with the variables, I've gotta mention the counterpart of the cout thing; the cin function thing.

As cout was involved with output, cin is involved with input. I'm gonna use them in my next code.

 

Let’s make an adder program.

 

 
#include <iostream>

int main()
{
 int x;
 int y;
 int z;

 std::cout << "Welcome to the adder program!n";

 std::cout << "Enter an integer: ";

 std::cin >> x;

 std::cout << "nNow enter another integer: ";

 std::cin >> y;

 z = x + y;

 std::cout << "nGreat! The sum is: " << z << "n";

 system ("pause");

 return 0;
}

 

Excellent, it works!

 

If you bother to compile it, it produces a program that displays a welcome, and waits for you to enter an integer.

 

After entering the integer and pressing enter, it asks for another integer.

After that, it's gives you the sum of the two integers.

 

Pretty cool.

 

The std::cin statement signals the computer to wait for the user to enter something using the standard input device. Note that or cin, we use << instead of the opposite pair as with the cout statements. Why, I don't know. Maybe just or kicks. I don't quite understand what the >> and << are all about. (Help!)

 

Anyway, we use a statement z = x + y;, and it associates the value of x + y to whatever is to the left of the '='. (In this regard, the '=' is an exception in the realm of C++, most of the other things such as '+', and '-' associate from left to right.)

 

 

Well, that's about variables.

 

There still remains the matter of types of variables. Apart from 'int', there are 'long int', 'short int', 'bool', ''float', 'double' and 'long double' to name a few. What they mean will be something I'll come across when I get to actually mess with them.

Link to comment
Share on other sites

rod, to make your life simpler:

 

#include <iostream>

//this does not declare the use of namespace std (and you have seen how many things go into that) this only declares use of std cin and cout (speciffically only the two)
using std::cout;
using std::cin;

int main()
{
 int x;
 int y;
 int z;

 cout << "Welcome to the adder program!n";

 cout << "Enter an integer: ";

 cin >> x;

 cout << "nNow enter another integer: ";

 cin >> y;

 z = x + y;

 cout << "nGreat! The sum is: " << z << "n";

 system ("pause");

 return 0;
}

 

Ok, so to help you with C++, i will attempt to teach certain aspects of it to you through code (anyone is welcome for the drive, everyone is welcome to comment and add on to what i miss)

 

//Reverse polish notation simple calculator:
#include<iostream>

//declare namespaces
using std::cin;
using std::cout;

int main()
{
   
   float first; //this will be the first operand as well as the answer (stupid to use up more space then needed)
   float second; //second operand
   short int op; //operator selection

   cout << "nPlease enter the first operand: ";
   cin >> first;
   cout << "nPlease enter the second operand: ";
   cin >> second;
   cout << "nNow let's select the operator:n1:+t2:-n3:*t4:/n";
   cin >> op;
   
   //switch operation to act on the above choice
   switch(op)
   {
             //default is addition
    case 2: //in case its subtraction
         cout << "nSubtactingn";
         first-=second;
         break; //so it exits the switch without going further
    case 3: //if its multiplication
         cout << "nMultiplyingn";
         first*=second;
         break;
    case 4: //division
         cout << "nDividingn";
         if(second!=0) //check for zero (lets be modern now)
         {
          first/=second;
          break;
         }
         cout << "nError: Division by zero!nExiting!"; //if it is a zero, we will hit this
         system("pause"); //pause for message
         return 1; //return one, one because then if you have another program tracking the progress of this one, you can have see that there was an error with the program
    default: //default addtition
             cout << "nSubtractingn";
             first+=second; 
             break;
    }
    //display the answer and congradulate users with saving one click ;)
    cout << "nThe answer is: " << first << "nCongradulations, you have saved 1 click!n";
    //pause before error message
    system("pause");
    return 0;
}

now the code is still very young, so i will add to it in the future to make it more secure (a lesson at a time :D ), so if you have any questions so far, ask them please :)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...