DJing Discussion

This area is for discussion about DJing in general. Please remember the community rules when posting and try to be polite and inclusive.

My Apologies To Rane & Serato

djtonypsalms 7:11 PM - 9 November, 2006
Apologies to Rane & Serato...

I Anthony aka DJ Tony Psalms apologize for making a bad decision and putting “File Sharing” on a flyer for Rane/SeratoScratchLive Session in L.A.

This was totally my mistake, and Rane/Serato had nothing to do with it. Although it was advertised it never happened. DJs on this forum can testify to that.

A Forum member brought this to my attention, and a Serato Rep wrote me a PM stating their strong feelings AGAINST file sharing.

As a result, and after giving this much thought, I’ve decided to make the next Rane/SeratoScratchLive Sessions Nov. 13th the last one.

Thanks to all who came and supported it, (rane & serato for the T’s & stickers) and I wish every one good luck with their DJing!

:)

Peace & One Love!

Anthony

P.S. For those genuinely concerned about why and how I came to this conclusion, get at me...

www.myspace.com
djmetaphysics 7:20 PM - 9 November, 2006
OOOOOO.. That type of stuff really erks them. I can only imagine how they feel after they helped you with the T's/promotion of the whole thing. Id prolly take the whole squad out to lunch or something if ever in the area. If I could even bring myself to show my face around them.
Julls 7:27 PM - 9 November, 2006
It takes a real man to step up to the plate and admit to being wrong! Much respect Tony for comming forward to apologize!
Kool DJ Sheak One 7:41 PM - 9 November, 2006
Shit was hella fun while it lasted so shortly. Fucked up that it had to come to this. Wish we lived in a world where shit can be worked out.Took balls to say you made a mistake. Much props. Hope you're happy Nik39!
DJ_Mike_Coquilla 7:45 PM - 9 November, 2006
Quote:
It takes a real man to step up to the plate and admit to being wrong! Much respect Tony for comming forward to apologize!
dittoe.

now for your punishment, you must mix Laffy Taffy & Sexy Back. and you aren't allowed to complain about the clashing BPMs :)
scotty B 7:47 PM - 9 November, 2006
Much respect for this post. I can vouch for being at every one and not even hearing the word Filesharing. It was a much aprreciated effort from Tony for putting this on...and the supprt from Rane. Is this really a reason to end it? Everyone makes mistakes... it was corrected. And since sharing never happened... No harm, No Foul right? Let's keep this good thing going.
nik39 10:18 PM - 9 November, 2006
Quote:
It takes a real man to step up to the plate and admit to being wrong! Much respect Tony for comming forward to apologize!

[...]

Much respect for this post.

Word.

Quote:
Hope you're happy Nik39!

This was not my intention, and you know that. I stated earlier that I find the SSL sessions a really cool idea to meet djs, share thoughts, ideas etc. I wish someone would organize something in my local area. So please hold back your comments, that my intention was to stop this idea.
nik39 10:22 PM - 9 November, 2006
Again, if I had had the impression that this was something by mistake I would have PM'ed him before asking him in public. As the same "filesharing" comment was also found on previous flyers, one can only come to the conclusion that it was not "just a mistake". Thats why I asked him in public what was going on with that.
Dj K.Smith 10:23 PM - 9 November, 2006
^^^ Too late dawg...

Thanks for the fun time (first session for me ) Tony... We'll have another SSL Jammy Jam sometime in the near future...
scotty B 10:33 PM - 9 November, 2006
Judging from any of nik39's posts I really don't think was trying to stop the sessions...
Kool DJ Sheak One 10:45 PM - 9 November, 2006
Quote:
Judging from any of nik39's posts I really don't think was trying to stop the sessions...

Yah, but Rane sent Ninjas to Tonys House. They were touched deeply. Im not saying Tony did'nt mess up, but neither is he. Somebody put the holy ghost in the Serato dudes to be really super pissed off before hearing both sides. They were like "How could you do this to us"!And shit is all uncomfortable now I guess.
djtonypsalms 11:02 PM - 9 November, 2006
Quote:
Again, if I had had the impression that this was something by mistake I would have PM'ed him before asking him in public. As the same "filesharing" comment was also found on previous flyers, one can only come to the conclusion that it was not "just a mistake". Thats why I asked him in public what was going on with that.


This is, for the most part, is how the first flyer looked like:

i6.photobucket.com

And here is the one that had the “file sharing” offer, which I’ve erased.

i6.photobucket.com

Can you please show me the “previous fliers” that mentioned “file sharing?”
papsworth 12:16 AM - 10 November, 2006
HAHAHAHA
DJ_QB 12:23 AM - 10 November, 2006
leave it to nik39 top flight security to have nothing better to do. good job nik maybe you will get that promotion to super cop and get that walkie talkie u've been waiting for.
mexicannnnnn 1:57 AM - 10 November, 2006
Serato sessions are a great idea... I'm going to see if I can start a bi-monthly session here in Toronto.
Serato, Support
Matt G 2:29 AM - 10 November, 2006
Quote:
leave it to nik39 top flight security to have nothing better to do. good job nik maybe you will get that promotion to super cop and get that walkie talkie u've been waiting for.


DJ_QB, go easy. No need for the attitude.
DJ Michael Basic 4:09 AM - 10 November, 2006
Sorry to say Matt, but if you look at a history of Nik39s posts, the attitude is warranted. This issue aside, nik39 is tattletale personified. It's really getting old.

As far as this issue goes, there was never any file sharing. I can say with certainty that not even a single mp3 was lifted off one computer and put on another. The only "files" that were "shared" was me putting the drivers for my ttm57 on a flash drive and giving them to the other DJs so they could try out the 57. I know at least one DJ (K Smith) who was eying the 57, and made his purchase of one after using mine at the first serato sessions.

I'm sure nik had "only the best intentions" in mind, and wasn't trying to end this thing, but nik is also tattletale personified, and his "intentions" are usually clouded by his, "I'm gonna tell on you!!!" attitude. Live and let live. Nobody here has been elected "puritan leader" of the serato boards. We don't need a shephard to steer us from wrong doing. All that had to be done was, someone send tony a PM saying, "Hey dude, take the words "File sharing" off your flier, someone might get the wrong idea" and it would have all been gravy. Having good intentions doesn't always mean you did the right thing. Maybe it's time our little e-deputy took some evaluation time.
Serato, Support
Matt G 4:33 AM - 10 November, 2006
DJ Michael Basic, nik39's activities in this forum are extremely helpful to us here at Serato. If he were to stop helping because people gave him a hard time, that would be a loss to us.
nik39 7:31 AM - 10 November, 2006
Quote:
Yah, but Rane sent Ninjas to Tonys House. They were touched deeply. Im not saying Tony did'nt mess up, but neither is he.

But this isnt something you can blame me for this misunderstanding, can you? I didnt put this stuff to the flyers, I didnt design them.

Quote:
Can you please show me the “previous fliers” that mentioned “file sharing?”

What I meant was, that you were using the same "file sharing" comment for previous SSL sessions, I've checked the flyers, and they had the same comment. I didnt know you were using generic flyers for at least the last 2 events.


Quote:
I'm sure nik had "only the best intentions" in mind, and wasn't trying to end this thing, but nik is also tattletale personified

Quote:
We don't need a shephard to steer us from wrong doing. All that had to be done was, someone send tony a PM saying, "Hey dude, take the words "File sharing" off your flier, someone might get the wrong idea" and it would have all been gravy.

Did you read my previous explanations why I didnt do it that way? I've PM'ed at least one user who was doing similar kind of stuff before, but that was where I had the impression that they did that by mistake and they didnt mean to promote filesharing. So please pass that buck to someone else.

Quote:
Having good intentions doesn't always mean you did the right thing.

Same goes for this file sharing comment. If someone reads that flyer he must come to the conclusion somthings fishy is happening there, regardless of what actually happened. Only a very small minority of people, actually those who attended, knew or could have known that no filesharing is happening. Is that the point? No, the point is that this was put on the flyers, anyone who reads the flyers MUST come to the conclusion

* DJs are file sharing
* are all "digital" DJs doing this kind of illegal stuff?
* as Rane/Serato is sponsoring these events, they must be aware of it. Is Rane supporting breaking of copyrights? Is Serato as a software company (who surely suffered from piracy as well) condoning theft of intelectual property and piracy?

This is the stuff which should come to the mind of anyone reading the flyers. I am not saying you actually file shared, but the intention was put on the flyers, thats doing enough damage already. After the horse has left the barn it's too late to close the door. Rane and Serato have often enough posted on this board what they think about file sharing, its their board, we users should respect that. BTW. there are also other DJs who share their point of view.

To end my bla bla, tonypsalms, I again truely appologize. It was not my intentions to either bash you nor to bring your events to an end. And all the previous bla bla was not directed at you, because you seem not to doubt the whole matter and that it was brought to the attention. You already apologized - a nice move. I hope you understand my point of view as well. Thanks for taking the time to read my bla bla ;)
ejayian 8:21 AM - 10 November, 2006
I dont know the whole story but since rane/serato was putting there official stamp on it shouldnt they have been aware of any material that was printed up?

Isnt there some kind of procedure for that type of thing especially when your a company as big as rane/serato? Shouldnt the flier been approved by rane/serato before being distributed?

When companies advertise rane/serato prodcucts arent those companies also given a set of rules they must follow eg you can only print this & you must not print this? Look at how strict they are when it came to designing the new 57 shirt.

I would have to say its partly rane/serato fault for not informing tony about what can & cant be done, if they did then tony screwed up and any form of apology doesnt really mean much..........

As far as Nik39 questioning djtony in public I dont know what post your all refering to but if its "officialy" sponsored by rane/serato i woude have to think rane/serato screwed up for approving the flier & questioned them first.
m0rph! 10:58 AM - 10 November, 2006
Quote:
DJ Michael Basic, nik39's activities in this forum are extremely helpful to us here at Serato. If he were to stop helping because people gave him a hard time, that would be a loss to us.

nik39 for President!
djtonypsalms 11:02 AM - 10 November, 2006
I'll ask again, and please show and prove...

Quote:
What I meant was, that you were using the same "file sharing" comment for previous SSL sessions, I've checked the flyers, and they had the same comment. I didnt know you were using generic flyers for at least the last 2 events.


Please... where are the previous fliers that contained "file sharing?"
djtonypsalms 11:06 AM - 10 November, 2006
First flyer:

i6.photobucket.com

Flyer in question...

i6.photobucket.com

+++++++++

Where are the other flyers that "had the same comment"?
djtonypsalms 11:08 AM - 10 November, 2006
EDIT:

Flyer in question:

i6.photobucket.com
Monk-A 1:34 PM - 10 November, 2006
will chekc your Myspace when i get home but I dont understand why you are stopping the Session tony?

I think if there was a wording problem and it's been resolved why not continue such a worthwhile meet...

I'm sure Nik wasn't being malicious just concerned and this seem slike a really resolvable problem so it's areal shame to see something like this dissapear because of bad wording...
Dj Metro 1:48 PM - 10 November, 2006
nik39 is a snitch...watch your laptop.... .. might go 4 a swim
shiestO! 2:38 PM - 10 November, 2006
wow.
Dj KaGeN 3:05 PM - 10 November, 2006
Why Why Why is nik39 always in a battle of semantics?

Other forums are much stricter and delete whole threads when they run astray or have content that is detrimental to the sale of the product. Would you prefer censorship like that instead? Would removing this thread and the other have been a better solution? Did you count the rules here, 3 -- pretty simple stuff. Elementary and yet so many of you still overlook and then later have squabbles over them. Nik39 is one guy here assisting (for free), and backed by Serato Employees for the greater good and you think he's a bad guy? Get the fuck over it already. This forum is going to hell cause of all you macho, pig headed fools can't follow a few rules, and want to put the gloves on since your delicate egos have been tarnished via an Internet forum of your peers, who most you will never come face to face with. Enough with the bullshit tennis-like banter.

Tony you stepped up like a man and apologized, but what is one to think after you continue to carry on in this fashion? If I may be of some assistance, I read all of the flyers. This last one was the only was that had anything questionable.

Case closed.
grrillatactics 3:28 PM - 10 November, 2006
Yeah, I wouldn't let a small squabble that is now resolved put an end to what I think is a brilliant idea for a recuring event.

KaGeN hit the nail on the head, too. There really are only 3 rules. I like how the mods don't just delete threads left and right, and if that means that we self-moderate to make sure the rules are followed, than that is cool with me. It is everyone's responibility to make sure that the rules are followed and that we are good ambassadors for the digital DJing community. Coming down on nik for actually helping out seems kind of silly. It was clear that he wasn't being malicious when he asked about this most recent flier.

And again, if the issue is resolved, keep doing the event. If I lived out that way, I would love to go.
grrillatactics 3:30 PM - 10 November, 2006
P.S. Tony, big up for stepping to the plate and taking responsibility, and also for doing what it took to put things right. Not everyone in this world is willing to take responsibility when things go wrong.
s42000 4:12 PM - 10 November, 2006
wow caramba !!
s42000 4:39 PM - 10 November, 2006
Filibuster! let it rest ladies ...

Chapter 1: C++ Basics
Welcome to C++! This first chapter will provide you with some basic foundational material you will need to progress through the rest of the book. In this chapter you will be introduced to the history of C++, the basics of the language, and how to use variables and write expressions in C++. These fundamental concepts are the essential building blocks that you will use to create C++ programs throughout the rest of this book.

History of C++
C++, as the name implies, is essentially based on the C programming language. Therefore, it seems prudent to begin with a brief history of C. The C programming language was devised in the early 1970s at Bell Laboratories by Dennis Ritchie. It was designed as a system implementation language for the Unix operating system. The history of C and Unix are closely intertwined. For this reason a lot of Unix programming is done with C. To some extent, C was originally based on the typeless language BCPL, however it grew well beyond that.

The C++ programming language was invented by Bjarne Stroustroup. Work on what would become C++ began in 1979. The initial version was called “C with Classes.” That name did not work out well, and was replaced with C++. The first version of C++ was used internally in AT&T in August 1983. The first commercial implementation was released in 1985. The C++ language standards are now handled by the American National Standards Institute (ANSI), and the International Standards Organization (ISO). This is why you often hear pure C++ referred to as ANSI Standard C++, or ISO Standard C++.

Hint! Pure C++ is mentioned because there are a lot of extensions that are specific to a particular compiler or operating system. A few of these are covered in this book, but are identified as being nonstandard.


There are several ways to write a C++ program. You could simply open your favorite text editor, such as notepad, write your program, save it, and then use a command line compiler to compile the program. In fact, this is the method that will be used in this book, until we get to Section IV, the section on Visual C++. If you have a commercial development tool such as Borland C++ Builder™ or Microsoft Visual C++,™then you must follow the instructions for that particular software package. The examples in this book will use the free downloadable version of the Borland C++ compiler. The free Borland C++ compiler does not have the extra development tools and IDE (Integrated Development Environment) that Borland C++ Builder has. The Web address to go to and download this free C++ compiler is listed in Appendix A. However, the free download is simply a command line compiler. A command line compiler is one that is executed from the command line. This, of course, begs the question of what is a command line. When you enter commands at a DOS prompt (Microsoft Windows™98), Command Prompt (Microsoft Windows 2000/XP), or Shell (Linux/Unix™) you are typing commands on a line, thus the term “command line.” You literally type in commands one line at a time. Figure 1.1 shows the basic DOS prompt for Windows 95/98™.

C++ Fundamentals
C++ is a programming language. As such, it shares a number of similarities with other programming languages. First we may need to clarify what a programming language is. A computer thinks in 1’s and 0’s. Various switches are either on (1’s), or off (0’s). Most humans, however, have trouble thinking in 1’s and 0’s. A programming language is a language that provides a bridge between the computer and human beings. A “low-level” language is one that is closer to a computer’s thinking than to a human language. A prime example would be Assembly language. A “high-level” language is one that is closer to human language. COBOL and BASIC are prime examples of high-level language. Many people consider C and C++ to be high-level languages, but actually C and C++ are both somewhat of a bridge between the low-level languages and high-level languages. You might think of them as mid-level languages. The level of a language, in this context, essentially refers to how far it is removed from actual machine language. It has no relationship to either the power of the programming language, or the difficulty of learning and using it. Various languages, with their basic level indicated, are shown in Figure 1.2.


Figure 1.2: Programming languages.
Each programming language has various strengths and weaknesses. Some, like BASIC, are easy to use but are neither flexible nor powerful. Others, such as Assembly, are powerful, but difficult to use. C and C++ are somewhere in the middle. C++ is quite powerful, but relatively easy to use (easier than Assembly but more difficult than BASIC). Some languages are also written with specific purposes in mind. Fortran was written specifically for mathematical programming, BASIC was designed simply for teaching programming, and COBOL was designed for business applications. C++ was designed as a general purpose language. It is used in business applications, telecommunications programming, artificial intelligence programming, games programming, and much more. This is one reason why it is the language that many teachers choose to teach students. Once you have learned C++, you can use it in a wide variety of situations.

Programs are written to handle data. This is why the industry as a whole is often referred to as data processing, information technology, computer information systems, and so on. That data might be information about employees, parts to a mathematical computation, scientific data, or even the elements of a game. No matter what programming language or techniques you use, the ultimate goal of programming is to store, manipulate, and retrieve data. Data must be temporarily stored in the program, in order to be manipulated. This is accomplished via variables. A variable is simply a place in memory set aside to hold data of a particular type. It is a specific section of the computer’s memory that has been reserved to hold some data. It is called a variable because its value or content can vary. When you create a variable, you are actually setting aside a small piece of memory for storage purposes. The name you give the variable is actually a label for that address in memory. For example, you might declare a variable in the following manner.

int j;
Then, you have just allocated four bytes of memory; you are using the variable j to refer to those four bytes of memory. You are also stating that the only type of data that j will hold, is whole numbers. (The int is a data type that refers to integers, or whole numbers.) Now, whenever you reference j in your code, you are actually referencing the contents being stored at a specific address in memory.

With that said, you might now be asking what is meant by “data of a particular type”? Data comes in different types. Some data consists of letters and some consists of numbers. Any programming language will recognize only certain types or categories of data. The basic data types that C++ recognizes, and what they hold, are shown in Table 1.1. In addition, there are a few other data types that will be introduced later in the book.

Table 1.1: Data Types Data Types
Values stored

int
This value is for whole numbers, or integers. The size depends on the operating systems. In 32-bit operating systems, the int is usually 32 bits (4 bytes) in length.

long
This data type holds larger whole numbers

float
Floats are used to hold decimal numbers such as 2.02798

double
A double is simply a really big float.

char
A char can store a single alpha-numeric type. In other words, it can store a number or a letter.

bool
Bool is short for Boolean, a reference to Boolean logic. Therefore, this data type can only store true or false.

short
This is basically a small integer. Usually 2 bytes in length. But the actually size will depend on the operating system. On 32-bit operating systems such as like Windows 98, 2000, NT, and XP, a short will be 2 bytes long.


When you are deciding what type of variable to create, you need to think about what kind of data you might wish to store in that variable. If you want to store a person’s age, then an int is a good choice. The int data type will hold whole numbers, and will, in fact, hold numbers much larger than you might need for a person’s age. The long data type will also hold whole numbers, but it is designed for even larger whole numbers. If you wished to store bank balances, grade point averages, or perhaps temperatures, you would need to consider using a float. The float data type holds decimal values. However if you were storing astronomical data, you would still want to hold decimals, but because they might be quite large, you would have to consider storing them in doubles. Picking what data type to use is actually simple. Just give some thought to the type of data you intend to store in a variable.

In addition to considering what type of variable you will use, you must also pay attention to how you name the variable. Only certain names are allowed in C++. Variable names must begin with a letter or underscore and may contain any combination of upper/lower case characters, digits, and underscores. Variable names can neither begin with a number nor contain certain symbols such as #, &, *, and so on. Here are some examples of valid and invalid variable names (Table 1.2).

Table 1.2: Valid Variable Names Valid Variable Names
Invalid Variable Names

Accountnumber
&account

_LastName
Last:Name

Length_of_side
#length

Temperature
$temp


In addition, many of the symbols that C++ does not allow you to use in naming your variables actually represent something important in the C++ programming language. This is one reason why such symbols are not allowed in variable names. Also, please understand that simply because a name is valid in C++ does not make it a good name. It is important that your variable names bear some resemblance to the value they hold. The compiler will certainly let you compile your code without this, but it will make your code much more difficult for other programmers to understand. If your variable holds an account number, please don’t name the variable x or i. Instead, give it a name such as account_number or acctnum.

Some programmers go further and add a notation at the beginning of the variable name to indicate what type of variable it is. For example, an account number that is an int might be called i_accountnum or intAccountNum. The following table shows common prefixes used for various data types. Not everyone follows these naming conventions. Nevertheless, they are common enough that you should be aware of them. They are summarized in Table 1.3.

Table 1.3: Naming Conventions Variable Type
Common Naming Conventions

int
iaccountnumber, i_accountnum, intaccountnum

float
fbalance, f_balance, flt_balance

long
lnumber, l_number, lngnumber

bool
b_isempty, bool_isempty

char
c_value, chrValue


There is a plethora of ways to name variables; no way is right or wrong. The thing to keep in mind is this: Does your personal naming convention make it easy for others to read your code? Does your variable’s name clearly identify what type of variable it is and/or what data it will hold? If you can answer yes, then your naming convention is fine.

Now that you know how to name variables, let’s give you a few examples.

int int_account_num;
boolean bturnedon;
float fltsalary;
Notice that these examples all obey the aforementioned rules for naming variables. You might, however, be curious about the semicolon at the end of each line. Each statement in C++ (as well as C, Sun Java, and several other programming languages) ends with a semicolon. The semicolon basically tells the compiler that you are done with that particular line of code, and that the things you have written prior to that semicolon represent one single, concise statement. A statement is simply a single line of code that performs some action. Many programmers also use the term expression when referring to a statement. The two terms, expression and statement, are interchangeable.

You can declare more than one variable on a single line. All the variables declared in that statement will be of the type you declared at the beginning of the statement.

int i_account_num, i_age, int_years_w_company;
All three variables are of type int.

Hint! This works the same way in many other programming languages such as Java and C, but does NOT work this way in Visual Basic™.

Watchout! C++ is case sensitive. Uppercase letters and lowercase letters are treated as two different letters. An A is not the same as an a. That means that int main() and int Main() are not the same thing. One of the most common mistakes beginners make is forgetting the case-sensitive nature of C++.


You can choose to initialize your variable to some default value when you create it. The following examples illustrate this.

int num = 0;
float number = 0.0;
A default value is simply some starting value that the variable will hold, by default, if no other value is placed into it. For example, if your program was storing data about people who recently received a high school diploma, you might wish to use a default value of 18, because that is the most probable age of a recent high school graduate.

Statements and Expressions
As you have already seen, a statement is simply a single line of code that performs some action. Remember that another word for a statement is an expression. In C++, a single expression does some type of action. That action might be to declare a variable, add two numbers, compare two values, or just about anything at all. It is also important to remember that all statements/expressions end with a semicolon. Another of the most common mistakes that beginners make is leaving off semicolons. Let’s look at a few simple statements.

int i_acctnum;
i_acctnum = 555555;
i_acctnum = i_acctnum + 5;
Each statement performs a different action—but it does perform some action—and it ends with a semicolon. The first statement/expression simply declares a variable. The second statement/expression sets that variable equal to some value. Finally, the last statement/expression performs addition and puts the answer in the variable that was previously declared.

Operators
You saw, at the end of the last section, the use of the + sign. This is an operator. An operator is simply some symbol that performs some action, usually a mathematical action, such as addition or subtraction. C++ supports a number of important operators that you will need to get familiar with. Let’s begin examining C++ operators, starting with the basic math operators, shown in Table 1.4.

Table 1.4: Operators Operator
Purpose
Example

+
To add two numbers
int answer; answer = 5 +6;

-
To subtract two numbers
int answer; answer = 10 –3;

*
To multiply two numbers
int answer; answer = 4 * 5;

/
To divide two numbers
int answer; answer = 7/3;

++
This is a special operator that simply ments the value by 1. You will see this used later in this book when loops are discussed.
int answer; incre answer++;

--
This is also a special operator that simply decrements the value by 1.
int answer; answer--;

=
The single equals sign is an assignment operator. It states “make what’s on the left equal to what’s on the right”
answer = 16;

==
The double equals is an equality operator. It asks “is what’s on the left equal to what’s on the right?” This is frequently used in if statements (which you will see in a later chapter!)
if(answer==5)

!=
Not equal to
if (x !=3)

+=
Add then assign
x += 1;

-=
Subtract then assign
x -=1;

||
This is the logical OR operator.
if(j == 5 || j ==10)

&&
This is the logical AND operator
if(j > 5 && j<10)

>>
Bitwise shift to the right
3<<2;

<<
Bitwise shift to the left
3>>2;

&
Bitwise And
3&2;

|
Bitwise Or
3|2

Watchout! When using the increment (++) or decrement (—) operator, it is necessary to be careful of where you put it. If you put the operator before the variable, then that operation will take place before any other operations in the expression. Some examples follow.

int answer, num;
num = 5;


Now using the expression,

answer = num++;
the value of num will first be put in answer, THEN incremented. In other words, the value of answer will be set to 5, and then the value of num will be incremented. If you want num to be incremented BEFORE you assign the value to answer then you must put the increment operator first, as shown in the following example.

answer = ++num;
The operators shown in Table 1.4 are your basic math operators and logical operators. There are several other operators you will also see in C++. These will be introduced in later chapters because they are pertinent to topics that will be covered in those chapters. Most of the operators in Table 1.4 should be familiar to you. The math operators represent simple math operations. All math operators occur with a specific order. The order is pretty much the same as the order of operations defined in mathematics. First is * (multiplication), next / (division), then + (addition), and, finally, – (subtraction). The increment ++ and decrement – operators precedence is determined by what side of the variable they are on. You can alter the order of operations by using parentheses, just as you do in mathematics. An example follows.

answer = x * 3 + 4;
First, x and 3 would be multiplied, and then 4 would be added to that product. If, instead, you wanted to add 3 and 4, then multiply by x, you could simply use parentheses to denote that.

answer = x * (3 +4);
The order of multiplication-division-addition-subtraction is simply the order defined by mathematics for these operations. Some teachers even use the mnemonic My Dear Aunt Sally to help students to recall the proper order of operations. The important thing to remember is that an operator is simply a symbol that defines some action to be taken. The + symbol defines the action of addition and the \ symbol defines the action of division. Other operators, such as the increment ++ operator, may be new to you, but the fact remains that they are simply symbols that define some action.

An operator is considered to be a unary operator if it takes only one argument. Put another way, if a symbol only acts on one number then it is a unary operator. The increment and decrement operators fall into this category. They only work on a single variable. Binary operators, on the other hand, work on two numbers. Addition and subtraction both work on two numbers. A more technical definition would be that binary operators are operators that take two arguments.


Basic Structure of a C++ program
Now that you have seen variable declaration, C++ expressions, and the basic math operators, let’s take a quick look at the basic structure of a C++ program. All C++ programs must have a main function. This is where the program begins. Chapter 4 goes into greater detail regarding functions. For now, suffice it to say that a function is one or more statements grouped together in a logical manner to accomplish some goal under a common name. Chapter 4 covers all the intricacies of C++ functions. The following is a basic C++ program.

int main()
{
return 0;
}

Now, this program will not do much—in fact, it won’t do anything useful at all. It is, however, a valid C++ program. It has a main function that returns an integer value. The main function is where all C++ programs start. This is the starting point for your entire program. All main functions are required by the ANSI (American National Standards Institute) standards to return an integer. The integer is a 0 if the program executes fine, and a 1 if some problem is encountered. This was originally done because some operating systems require any program to return a value telling the operating system that everything is OK. You will see a lot of Windows programmers use a main function that returns a void like the following.

void main()
This will work in some cases, but it is not technically correct. This book endeavors to conform to the ANSI standards and use return 0.

The next thing to notice about our sample program is the presence of brackets. These brackets are C++’s way of establishing borders around any block of code. (Incidentally, C, Java, and JavaScript™ do the same thing. Learning it here will help you learn other languages as well.). Every time you see an opening bracket, {there must be a matching} closing bracket. You will see a lot more about this when we discuss loops, decision structures, and functions. For now, suffice it to say that brackets form borders around blocks of code.

With all that said, let’s look at a program that has a few statements.

int main()
{
int j;
j = 5;
j++;
return 0;
}
This simple program creates a variable named j, sets the value of that variable to 5, then increments that value by one. This is still not a particularly exciting piece of code, but it does illustrate the basic structure of a C++ program. Three statements are executed, a 0 is returned to indicate that everything is OK, and there are brackets surrounding the main function. If you carefully examine this code, and follow this template in all your programming, then you will do well!

Header Files
There is only one more item that needs to be discussed regarding the basic structure of a C++ program. That item is header files. Header files are files that contain the definitions for functions and/or classes. Basically, if you have a lot of functions or variables that you might want to use in several programs, you can put them in a header file, then include that header file anywhere you need to use it. After creating a header file you can then include a reference to a header file in your program and use the functions and/or classes defined in that header file. The real intricacies of header files are discussed in a later chapter, in which you will actually create some header files. However, you should realize that there are a lot of these files built into C++ that you can use! Well, “built in” is not exactly accurate. They are actually installed with your compiler and you can include them in your programs. One of which you will use in Chapter 2 is the iostream header file. It gives you functions to handle input and output from the screen. The way you include any header file is simple. At the beginning of your file, you reference the header file. This is demonstrated in the following example.

#include <iostream>
int main()
{
return 0;
}
You now have access to all the classes and functions defined in the iostream header file. In the following chapters, you will see several different header files, each providing a different set of functions for you to use. For now, all that is important is that you realize that you include a header file using the # sign and the word include. If the header file is one that is part of C++, then you simply use the <headerfilename>. Make sure that this is the first thing you do in your file! Remember that you use .cpp to indicate a C++ source file and .c to indicate a C source file, while the .h indicates a header source file. A source file is simply a plain text file that has the source code for your C++ program. Source code is the basic lines of programming language that you write, and that the compiler will later use as a source to create an executable program.

Hint! C requires you to specify the .h in the file. For example, screen input and output is implemented in C using the <stdio.h> header file. The .h extension is not needed in C++. Many compilers will support it, but not all. It is best to refer to <iostream> rather than <iostream.h>. It is also important to realize that the ISO and ANSI C++ standard dictates that, unless you are using an old C-styled header file, you will not add the .h extension.

Function Basics
What are functions? In simple terms, a function is a block of code that is identified by some name and can take zero or more parameters and can return some value. That definition probably does little to clarify the issue for you! Let’s look at a function and its parts to help clarify this issue. To begin with, consider the following function, which squares a number.

float square(float num)
{
float answer = num * num;
return answer;
}
The first line of the function is called its declaration line. It has three parts. The first part is its return type. The return type tells you what kind of data the function will give you back. If it returns nothing, then its return type would be void. In the previous example, the function will return the answer to our math problem, and that is a float. The second thing is the name of the function. Function names follow the same guidelines as variable names. It is a good idea to have the function name reflect what the function will do. Next, inside the parenthesis, we have parameters. A parameter is some value you pass to the function in order for it to work. For example, in this case, to square a number, we have to give it the number to square. Students often ask: “What do we need to put as parameters? Do we even need any parameters for this function?” There is a simple way to answer this question for any function you write. Ask yourself this question: If you wanted some person to do this task for you, would you need to give them anything? And, if so, what? If you wanted a person to square a number for you, you would have to give them that number. However, if you just wanted them to say hello, you would not have to give them anything. Therefore, a function that squares a number should take one parameter, and a function that displays hello on the screen might not take any parameters. There will be a lot more in-depth discussion on functions in Chapter 4.

Variable Scope
In the beginning of this chapter, you were introduced to the concept of variables. You saw the various data types, how to declare a variable, and what proper names you could use for variables (as well as ones you could not). There is one more topic concerning variables. This had to be left until after the discussion about the structure of a C++ program, and you will see why shortly. The topic at hand concerns WHERE you declare a variable. This is called variable scope. Consider the following example.

int main()
{
int j;
return 0;
}
This variable is declared inside the main function. That means it is only usable within that function. If you create other functions, they will not be able to access the variable j. This is referred to as a local variable. A local variable is a variable that is declared within a function, or within any block of code. Now let’s look at another example.

int j;
int main()
{
j++;
return 0;
}
Notice that j was NOT declared inside the main function. It was declared outside of any function. This means that it can be used throughout your code. A variable declared outside of any function can be used in any function, and is referred to as a global variable. This is referred to as variable scope. Scope defines the range within which a variable can be used. If the variable has local scope, then its range is restricted to the function in which it was declared. It is essential to pay attention to the scope of your variables. It is not uncommon for a beginner to declare a variable inside one function, and then forget that it is only usable within that function.


Compiling
When you write a program you are typing in code. You might be simply typing code into a basic text editor or into a commercial IDE (Integrated Development Editor) such as Borland C++ Builder or Microsoft Visual C++. But you will not be distributing what you are typing to end-users. What do you distribute to them? First of all, what you type is the source code. It is not an executable program. Remember that the source code is simply all the programming commands that you write. The process of taking your source code and creating an executable is called compiling. The purpose of a compiler (whether it’s a command line compiler, or one built into some commercial IDE) is to translate the specific programming language code you wrote into standard machine instructions that the computer can understand and run. That code is in a binary data file (1’s and 0’s) that the machine can understand and execute (thus, the term executable).

The specifics about how you compile a program depend on the compiler you are using. Commercially available development kits such as C++ Builder and Visual C++ usually have a button to press, or a drop-down menu to select. Command line compilers require you to type in compilation instructions at the command line. The specifics for using the free Borland C++ compiler used in the examples in this book are given in Appendix D.


After you have worked out code that does some particular action, what happens when the code has to be modified 6 months later? You probably won’t remember what you were thinking or intending when you wrote the code, and you will have to spend significant time just trying to remember what you were trying to do. It is even worse if you have to modify someone else’s code. Well, never fear—there is an answer. C++ (as well as all other programming languages) provides a way for you to put comments in your code. A comment is simply an explanatory note that the compiler will ignore. Comments are for the programmer working on the code to read, not for the compiler. There are two ways to make a comment. The first is to put two forward slashes // at the beginning of that line, like you see in the following example.

// This variable is used to hold account numbers
int account_num;

The compiler will ignore the comment, but any programmer working on the code can read it to see what the code in question was meant to do. It is a common practice to put a few lines of comments at the beginning of a function, to explain the basic purpose of that function. Another way to make comments, if you have several lines of comment, is to enclose the comments with a beginning forward slash asterisk /* and end the comments with an asterisk forward slash */. Here is an example.

float square_number(float num)
{
/* This function takes in a single number then squares
that number
(multiplies it by itself) and returns the answer */
return num*num;
}
Functions are simple. As such, some programmers skip comments all together. Your code will compile and run without comments. However, when you have to come back later and modify the code, you will be sorry if you did not comment it properly. I strongly encourage you to start early using comments in your code. Throughout the rest of this book you will frequently see comments used.


Chapter 2: Console Input and Output
Download CD Content
The previous chapter introduced you to some basics of C++ programming. This chapter covers another vital part of C++ programming: getting input from the user and displaying the results. This chapter concentrates on getting that input and providing the required output. This chapter focuses on doing this from some command line such as the Windows DOS prompt/command prompt, or a Unix/Linux shell. This means that you will learn how to take in what the user types, and to display results in a text format, back to the user. Obviously a program that does not take in input, or give back output, is ultimately useless, so please pay particular attention to this chapter.

Output to the screen
You will often want to provide the user with some type of text. It might be a message to the user, a request for input, or the results of some data that the program has computed. How do you take data from your program and convert it into some representation on the screen? Luckily for you, C++ provides some functions that handle screen output for you. All you have to do is learn how to use these functions. These functions are found in one of the header files that was mentioned in Chapter 1. The particular file you need to include is the iostream file. You include this by simply placing the following line at the top of your source code file.

#include <iostream>
Recall from Chapter 1 that, when you include a header file, you have access to all the functions defined in that file. By including this file you will have access to a number of functions for input and output. The two most important functions are cout and cin. Virtually all your input and output needs (at least for keyboard input and screen output) can be handled by these two functions. The first, cout, is how you display data to the screen. The following example shows the ubiquitous “hello world” program. (It seems like every programming book uses this example, so who are we to argue with tradition?)

Example 2.1
Step 1: Enter the following code into your favorite text editor then save the file as example02-01.cpp.

#include <iostream>
using std::cout;
using std::cin;
int main()
{
// Print hello world on the screen
cout << "Hello World";
return 0;
}

Step 2: To compile this, simply type the code into a text file and save it as hello.cpp. Then you will run your command line compiler by typing in bcc32 hello.cpp. If you typed in the code properly you will then have a hello.exe, that you can run any time you wish.

Step 3: Run the executable you just created. When you run it, it should look similar to Figure 2.1. (This image is from the command prompt of a Windows 2000 professional machine. A Linux shell would look a little bit different, but would be essentially the same concept.)


Figure 2.1: Hello World.
This may not be a particularly exciting program, but it does illustrate the basics of screen output. Notice that after we included <iostream> we also had two strange-looking lines of code.

using std::cout;
using std::cin;
cout and cin are both defined inside of the iostream header file. You have to tell your program which parts of iostream you wish to use. These two lines of code tell the compiler that you wish to use cout and cin. (cin will be described in detail later in this chapter.)

The cout command tells the C++ compiler to redirect the output to the default display device, usually that’s the monitor. cout is short for “console output.” Notice the << after the cout. The arrows literally point you in the direction the text will be sent. In the case of cout, the code is sent out of the program, thus the arrows point out of the code! This seems pretty simple so far, and it should. Now, what if we wish to format the code that we output in some special way? For example, when a program is done, the Windows 2000 command prompt (and earlier Windows DOS prompts) adds on the phrase “press any key to continue.” Perhaps you would like to place that on a separate line, to separate it from the output you are producing. That would be the logical thing to do because you do not wish to confuse the user into thinking that “press any key to continue” is your program’s output. Fortunately for you, C++ provides several formatting codes that you can add to any string to format it. For example, the \n code tells the C++ compiler to start a new line. Let’s rewrite the “hello world” program with this addition.

Example 2.2
Step 1: Type the following code into your favorite text editor and save it as example02-02.cpp.

#include <iostream>
using std::cout;
using std::cin;
int main()
{
cout << "Hello World \n";
return 0;
}
Step 2: Compile the code by running bcc32 example02-02.cpp.

Step 3: Execute the compiled code by typing example02-02. You should see an image like that depicted in Figure 2.2.


Figure 2.2: Hello World 2.
Note that anything after “Hello world” is on a new line. That’s exactly what the \n command means; it means start a new line. There are actually several commands that you can execute in this manner to format the code in any way you like. These codes are often referred to as escape codes. Table 2.1 summarizes most of them for you.

Table 2.1: Escape Codes. Escape Sequence
Represents

\n
New line

\r
Carriage return

\b
Backspace

\t
Horizontal tab

\’
Single quotation mark

\f
Form feed

\a
Bell (alert)

\v
Vertical tab

\\
Backslash

\”
Double quotation mark

\?
Literal question mark


As you can see, there is a plethora of options for formatting output to the screen. Throughout this chapter and the next you will see several of these codes used in examples. This table provides a summary of the escape characters you can use. You should recall from Chapter 1 that C++ is built on the framework of C. These formatting keys (also called escape keys) are a prime example. These keys work exactly the same way in C as they do in C++. The following is an example that illustrates everything covered thus far.

Example 2.3
Step 1: Enter the following code into a text editor of your choice and save it as example02-03.cpp.

#include <iostream>
using std::cout;
using std::cin;
int main()
{
// the following code demo's various escape keys
cout << "\" Hello World \" \n";
cout << "C++ is COOL! \n \a";
return 0;
}
Step 2: Compile the code by typing in bcc32 example02-03.cpp.

Step 3: Run your code by typing in example02-03.

If you entered the code in properly you will here a beep. (Remember that \a causes a beep.) You will see something similar to the image shown in Figure 2.3.


Figure 2.3: Hello World 3.
You should notice several things about this code. First, notice that you can place more than one escape sequence in order. You should notice that this was done in this example. You can use as many escape characters as is necessary in a given string of characters. You should also notice that the way to place quotes inside a string of characters is to use the proper escape character.

Watchout! If you try to simply put quotes inside of quotes, then your quotes will terminate the string. You must use the escape character. If you think about this, it makes perfect sense. As soon as the C++ compiler sees the quotation marks (if they are not preceded by the \) it will think that your string is now ending.


Finally, you should also notice the “beep” provided by \a. It is often useful to provide the user with audio signals in addition to visual signals.

Using these various escape sequences you manipulate the output of your program in a variety of ways. You can also, as you have already seen, create some audio output. The following example should illustrate this to you.

Example 2.4
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
using std::cout;
int main()
{
cout << "As you can see these \" escape keys \" \n";
cout << "are quite \'useful \' \a \\ in your code \\ \a
\n";
return 0;
}

Step 2: Compile that code.

Step 3: Execute the code. You should see something similar to Figure 2.4.


Figure 2.4: Using various escape keys.
These keys give you a wide range of formatting options as well as some sound effects. You will probably find these escape keys quite useful in your various programming projects.

In addition to the escape keys you have already seen, there are some other techniques for manipulating your output. For example, you will frequently see C++ programmers choosing the endl command for a new line at the end of screen output, rather than the escape key \n. To use endl just end your quotation marks, then type the << endl command, and terminate it with a semicolon. The following example demonstrates this.

Example 2.5
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
cout << "You have previously used the \\n key to get a
new line \n";
cout << "However you can also use the endl
command"<<endl;
return 0;
}
Watchout! You will notice that two of the lines of code in this sample wrap to the next line. This is simply a book formatting issue. When you type code into your text editor, put everything on one line, up to the semicolon.


Step 2: Compile that code.

Step 3: Execute the code. You should see something similar to what is displayed in Figure 2.5.


Figure 2.5: Using endl.
As you can see, the endl is just as useful in creating a new line. From a technical perspective, it also flushes C++’s buffer stream. What that means is that as you send content to the screen via cout, it is placed in a temporary buffer. The endl command causes that buffer to be emptied.


Chapter 3: Arrays, Strings, and Bitwise Operations
Download CD Content
In Chapter 1 you were introduced to variables. In Chapter 2 you used these variables in different ways, and the concept of an array was introduced. This chapter explores arrays in greater detail. This chapter also explores strings. Strings and arrays are closely related topics. Also included in this chapter is an introduction to bitwise operations.

Arrays and Strings
Now you have seen the basic data types you can work with in C++. These will be adequate for most situations. However, they will not be the ideal solution for all situations. In some situations, you have closely related data that should logically be grouped under a single name. For example, if you wished to hold the temperature for 20 consecutive days, all the values could logically be called “temperature,” but how do you have one variable hold 20 different values at the same time? The answer is an array. An array is basically a variable that can hold multiple values. A more formal definition would be an array is a series of variables of the same type, referred to by the same name, and contiguous in memory. Each variable in the array has the same name, and is differentiated by a number that indicates which element in the array it is. The following example declares an array.

float temperature[20];
What happens with this statement is that a variable named temperature is created, but rather than just the space for a single float value being allocated, space is allocated for 20 different floats. They are loaded into memory right next to each other in order starting with zero as the first element: temperature[0], temperature [1], temperature[2], and so on. Those floating point values can be accessed using a number to designate the element in the array you wish to address, like the following example.

temperature[0], temperature[1], temperature[2]….temperature[19]
Note that the temperature array stops at 19. It begins at 0 and has 20 elements, thus stopping at 19. All arrays begin with zero. If you define an array, the number you put in the brackets is the number of elements the array will have, beginning with zero.

Another way to define arrays is to say that they are simply a series of elements of the same type placed consecutively in memory. These elements can be individually referenced by adding an index to a unique name. In practical terms, this means that if we declare an integer array with five elements, then we can store five values of type int without having to declare five separate variables, each one with a different identifier. Instead, we can use an array to store the five different values of the same type.

You can access an element of an array the same way you would access any other variable; you simply have to provide the index that identifies which element of the array you wish to access.

temperature[5] = 89.5;

Watchout! If you attempt to access an element of the array that is beyond the bounds that you declared the array, most C++ compilers will let you try. . . . Unfortunately, this can lead to serious problems. The following example uses a value that is beyond the actual range of the array.


Example 3.1
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
using namespace std;
int main()
{

int myarray[5];
myarray[10] = 99;
cout << myarray[10] << endl;
return 0;
}
Step 2: Compile and run the code. You should see something similar to what is depicted in Figure 3.1.


Figure 3.1: Overflowing arrays.
When you write values beyond where you defined the array, there is no way to know where that variable was stored. Basically it is stored at some spot in memory. Because we tried to access an element that was six elements beyond an array of integers, what happens is that the next space in memory that is 24 bytes (six elements multiplied by four bytes per integer) is overwritten with the number 99. This could be memory that contains data that is necessary for some other program. Writing beyond the limit of your array is called overflowing the buffer. This can lead to serious problems because you might be overwriting some other program’s data. You should always be careful in your code to avoid attempting to access any element beyond the limits that you declared when you created your variable.

Before moving on, it is important that you fully understand what an array is. Many beginning programmers make this more difficult than it really is. An array is just another variable. However, instead of holding a single value, it holds a series of values. This is useful when you have data that is related. You can store each item in an element of the array. Therefore, an array is simply a series of variables with the same name and type, each designated by an index number, which identifies which element of the array we are addressing. You will notice that the past few paragraphs have given you a few different but similar definitions of an array. This is intentional. It is hoped that at least one of these definitions will help you to understand the concept. To illustrate how to access each element in an array, consider the following code fragment.

istudentsage[5];
studentsage [0] = 14;
studentsage [1] = 17;
studentsage [2] = 15;
studentsage [3] = 14;
studentsage [4] = 16;

You can see that an array named studentage is created. It is five elements long, ranging from mystudent[0] to mystudent[5]. We then place a value in each of the elements of this array. You could, of course, have made five different int variables, each with a different name. However, because they all contain the same kind of information, an array makes better sense. Let’s look at the following example.

Example 3.2
Step 1: Write the following code into your favorite text editor. Save it as 03_02.cpp.

#include <iostream>
using namespace std;
int main()
{
float temp[5];
cout << "Please enter the temperature for day one \n";
cin >> temp[0];
cout << "Please enter the temperature for day one \n";
cin >> temp[1];
cout << "Please enter the temperature for day one \n";
cin >> temp[2];
cout << "Please enter the temperature for day one \n";
cin >> temp[3];
cout << "Please enter the temperature for day one \n";
cin >> temp[4];
cout << " The temperatures for the first five days is ";
cout << temp[0] << ", " << temp[1] << ", "<< temp[2]
<< ", "<< temp[3] << ", ";
cout << temp[4] << endl;
return 0;
}
Step 2: Compile and run the code.

You should see an image, much like the one shown in Figure 3.2.


Figure 3.2: Using arrays.
This example is pretty simple but it does show you the basics of declaring an array, filling an array, and printing an array.

It is also important to initialize arrays to some default value. A default value is simply some starting point value. It is commonplace to give all numeric variables a value of zero. When declaring an array that has local scope (local scope refers to anything that is declared within a function), if you don’t specify otherwise, it will not be initialized. This means that its content is undetermined until we store some values in it.

If we declare a global array (a global variable is one which is declared outside of any individual function), its content will be initialized with all its elements filled with zeros (if it’s a numeric data type). What this means in practical terms is that arrays declared within a function must be initialized to some default value. Those declared outside of function don’t have to be initialized, but may be if you wish. If you want to play it safe, initialize all arrays to some default value, regardless of where they are declared. This initialization can take place in several ways. The most common way is done when you first create the array.

int myarray [5] = { 10, 5, 10, 20, 15 };
The other way to initialize an array is to use a loop and loop through each element, giving it a value. Chapter 5 discusses loops in greater detail. For now you can simply use the first method for initializing arrays. It is, by far, the most common method.

The arrays you have seen are called one-dimensional arrays, because they only have one dimension. However, you can have more dimensions to your array. Let us examine the two-dimensional array. When you declare a two-dimensional array you must declare two different indexes, as you see in the following example.

int myarray[4][4];

This expression creates an array of integers that is four integers by four integers, thus holding a total of 16 integers. You access each element of a two-dimensional array by specifying two numbers. For example, the first element of this array would be myarray[0],[0]. The following table (Table 3.1) clarifies the positioning of elements in a two-dimensional array.

Table 3.1: Two Dimensional Array Elements 0,0
0,1
0,2
0,3

1,0
1,1
1,2
1,3

2,0
2,1
2,2
2,3

3,0
3,1
3,2
3,3


It is possible to create arrays with any number of dimensions that you see fit. However, it is rare to see arrays of more than two dimensions. There are several reasons for this. The first reason is that such multidimensional arrays quickly become very unwieldy for the programmer. Secondly, they quickly tax a system’s resources. Consider that a single dimensional array of four integers has 4 elements and takes up 16 bytes (4 bytes per integer multiplied by 4 integers). A two-dimensional array of 4 integers by 4 integers has 16 elements and uses 64 bytes (16 bytes per row by 4 rows). But a three-dimensional array of 4 x 4 x 4 integers would have 64 elements and would take up 256 bytes. In most cases you will encounter single arrays, and occasionally you will see two-dimensional arrays. It would be rare for you to need to work with arrays of higher dimensions. Perhaps it would be useful for you to see an actual two-dimensional array in action. This example will use a 4 by 7 float. This represents 4 weeks, at 7 days per week, and the temperatures recorded on each day. This single, two-dimensional array can store the temperatures measured for 28 consecutive days.

Example 3.3
Step 1: Enter the following code into your favorite text editor and save it as 03-03.cpp.

#include <iostream>
using namespace std;
int main()
{
int monthlytemps[4][7];
cout << "Enter the temp for week 1 day 1";
cin >> monthlytemps[0][0];
cout << "Enter the temp for week 1 day 2";
cin >> monthlytemps[0][1];
cout << "Enter the temp for week 1 day 3";
cin >> monthlytemps[0][2];
cout << "Enter the temp for week 1 day 4";
cin >> monthlytemps[0][3];
cout << "Enter the temp for week 1 day 5";
cin >> monthlytemps[0][4];
cout << "Enter the temp for week 1 day 6";
cin >> monthlytemps[0][5];
cout << "Enter the temp for week 1 day 7";
cin >> monthlytemps[0][6];
cout << "Enter the temp for week 2 day 1";
cin >> monthlytemps[1][0];
cout << "Enter the temp for week 2 day 2";
cin >> monthlytemps[1][1];
cout << "Enter the temp for week 2 day 3";
cin >> monthlytemps[1][2];
cout << "Enter the temp for week 2 day 4";
cin >> monthlytemps[1][3];
cout << "Enter the temp for week 2 day 5";
cin >> monthlytemps[1][4];
cout << "Enter the temp for week 2 day 6";
cin >> monthlytemps[1][5];
cout << "Enter the temp for week 2 day 7";
cin >> monthlytemps[1][6];
cout << "Enter the temp for week 3 day 1";
cin >> monthlytemps[3][0];
cout << "Enter the temp for week 3 day 2";
cin >> monthlytemps[3][1];
cout << "Enter the temp for week 3 day 3";
cin >> monthlytemps[3][2];
cout << "Enter the temp for week 3 day 4";
cin >> monthlytemps[3][3];
cout << "Enter the temp for week 3 day 5";
cin >> monthlytemps[3][4];
cout << "Enter the temp for week 3 day 6";
cin >> monthlytemps[3][5];
cout << "Enter the temp for week 3 day 7";
cin >> monthlytemps[3][6];

cout << "Enter the temp for week 4 day 1";
cin >> monthlytemps[4][0];
cout << "Enter the temp for week 4 day 2";
cin >> monthlytemps[4][1];
cout << "Enter the temp for week 4 day 3";
cin >> monthlytemps[4][2];
cout << "Enter the temp for week 4 day 4";
cin >> monthlytemps[4][3];
cout << "Enter the temp for week 4 day 5";
cin >> monthlytemps[4][4];
cout << "Enter the temp for week 4 day 6";
cin >> monthlytemps[4][5];
cout << "Enter the temp for week 4 day 7";
cin >> monthlytemps[4][6];
return 0;
}// end of main
Step 2: Compile and run the program.

You should notice several things about this little piece of code. The first thing you should notice is the way in which the array is being filled. This is actually a rather inelegant way to fill the array. When you encounter loops in Chapter 5, you will see more efficient ways to fill an array, and to access its elements. The important thing for you to notice now is that 28 temperature values are stored in a single array.

Keyboard Input
You can now display text to the screen. It is also a good idea to get data in from the user. Fortunately, C++ makes that just as easy as output. In fact, it is done in a similar manner. Just as output is handled with the cout command, input is handled with the cin command. There are really only two differences. The first difference is that the arrows point into the program >>. (That’s logical, isn’t it?) The second difference is that the arrows must point to some variable. This makes sense if you think about it. If you are going to take input from the keyboard, you have to put it somewhere. An example follows.

Example 2.6
Step 1: Type the following code into your favorite text editor.

#include <iostream>
using std::cout;
using std::cin;
int main()
{
// variable declarations
int number1, number2, product, sum;
// get the users input
cout<<"Please enter an integer (whole number) \n";
cin >> number1;
cout<< "Please enter another integer (whole number)
\n";
cin >> number2;
// compute the answers
product = number1 * number2;
sum = number1 + number2;
// print out the answers
cout << "The sum of " << number1 <<" and " <<
number2 << " is " << sum <<"\n";
cout << "The product of " << number1 <<" and " <<
number2 << " is " << product <<"\n";

return 0;
}
Step 2: Compile the code by typing in bcc32 example02-06.cpp at the command line.

Step 3: Run the program by typing in example02-06. You should see an image much like the one displayed in Figure 2.6.


Figure 2.6: Input/Output and basic operators.
There are a number of items in this program that you should be aware of. The first is the use of the cin command. After declaring integer variables to hold the input, it is also necessary to use the command cin >> number1. That expression literally takes the input from the keyboard and places it into the variable number1. In this code you see the same thing done with the variable number2. Also notice that when you take in input you don’t need to do anything to tell the compiler what kind of variable you want to put the data in. The cin command can see what kind of variable is to the right of the >> sign, and will convert the data to the proper type, if possible. Obviously if you try to put a into an int, you will have a problem.

Watchout! Make sure that the variable you use for input matches the type of data you asked the user to enter. Do not ask for a decimal value then try and put that into an integer variable!


The next item that you should direct your attention to is the use of compound cout statements. You can output just about as much as you like with the cout command, in a single statement. All you must do is to separate the items you wish to output with << characters. Using this technique, you will be able to combine variables and text to form the output to the screen that displayed the answers. This is an important technique to remember. You will see it used many times in this book.

These simple examples demonstrate the basics of C++ input and output. With just these simple techniques you can handle input from the keyboard as well as output to the monitor screen.

Other Input Options
As you have already seen, the cin operator allows you to input data from the keyboard. However, it is not the only method or necessarily the best for all situations (but it is the simplest). The two other most commonly used methods are get and getline. The get function will retrieve a single character, no matter how much the user types in. The getline function will retrieve a certain number of characters, a number that you specify. This is particularly important when putting the data into an array.

Hint! Arrays are covered in detail in Chapter 3. For now you should simply think of an array as a string of variables, as you saw with the character array, buffer.


Simply using the cin will allow the user to try and put more characters into the array than it can hold. This is referred to as overflowing. The getline function allows you to specify how many bytes you will get from the user’s input. Each character the user types takes up one byte. So if, in the getline function, you specify four bytes, and the user types in the word computer, you will only retrieve comp, the first four letters. In the following example you will see the getline function used with an array.

Example 2.7
Step 1: Write the following code into your favorite text editor.

#include <iostream>
using std::cin;
using std::cout;
int main()
{
char text[10];
cout << "Please enter a word\n";
cin.getline(text,10);
cout << text << endl;
return 0;
}
Step 2: Compile and run the program.

Step 3: Type in more than 10 characters. You should see something like what is depicted in Figure 2.7.


Figure 2.7: The getline function.
You should notice that only 10 characters are placed in the character array, no matter how many you enter. In fact, you should probably prove this to yourself by deliberately typing in more text. This means that getline is the safe choice if you want to enter a string of characters into an array.



Keyboard Input
You can now display text to the screen. It is also a good idea to get data in from the user. Fortunately, C++ makes that just as easy as output. In fact, it is done in a similar manner. Just as output is handled with the cout command, input is handled with the cin command. There are really only two differences. The first difference is that the arrows point into the program >>. (That’s logical, isn’t it?) The second difference is that the arrows must point to some variable. This makes sense if you think about it. If you are going to take input from the keyboard, you have to put it somewhere. An example follows.

Example 2.6
Step 1: Type the following code into your favorite text editor.

#include <iostream>
using std::cout;
using std::cin;
int main()
{
// variable declarations
int number1, number2, product, sum;
// get the users input
cout<<"Please enter an integer (whole number) \n";
cin >> number1;
cout<< "Please enter another integer (whole number)
\n";
cin >> number2;
// compute the answers
product = number1 * number2;
sum = number1 + number2;
// print out the answers
cout << "The sum of " << number1 <<" and " <<
number2 << " is " << sum <<"\n";
cout << "The product of " << number1 <<" and " <<
number2 << " is " << product <<"\n";

return 0;
}
Step 2: Compile the code by typing in bcc32 example02-06.cpp at the command line.

Step 3: Run the program by typing in example02-06. You should see an image much like the one displayed in Figure 2.6.


Figure 2.6: Input/Output and basic operators.
There are a number of items in this program that you should be aware of. The first is the use of the cin command. After declaring integer variables to hold the input, it is also necessary to use the command cin >> number1. That expression literally takes the input from the keyboard and places it into the variable number1. In this code you see the same thing done with the variable number2. Also notice that when you take in input you don’t need to do anything to tell the compiler what kind of variable you want to put the data in. The cin command can see what kind of variable is to the right of the >> sign, and will convert the data to the proper type, if possible. Obviously if you try to put a into an int, you will have a problem.

Watchout! Make sure that the variable you use for input matches the type of data you asked the user to enter. Do not ask for a decimal value then try and put that into an integer variable!


The next item that you should direct your attention to is the use of compound cout statements. You can output just about as much as you like with the cout command, in a single statement. All you must do is to separate the items you wish to output with << characters. Using this technique, you will be able to combine variables and text to form the output to the screen that displayed the answers. This is an important technique to remember. You will see it used many times in this book.

These simple examples demonstrate the basics of C++ input and output. With just these simple techniques you can handle input from the keyboard as well as output to the monitor screen.

Other Input Options
As you have already seen, the cin operator allows you to input data from the keyboard. However, it is not the only method or necessarily the best for all situations (but it is the simplest). The two other most commonly used methods are get and getline. The get function will retrieve a single character, no matter how much the user types in. The getline function will retrieve a certain number of characters, a number that you specify. This is particularly important when putting the data into an array.

Hint! Arrays are covered in detail in Chapter 3. For now you should simply think of an array as a string of variables, as you saw with the character array, buffer.


Simply using the cin will allow the user to try and put more characters into the array than it can hold. This is referred to as overflowing. The getline function allows you to specify how many bytes you will get from the user’s input. Each character the user types takes up one byte. So if, in the getline function, you specify four bytes, and the user types in the word computer, you will only retrieve comp, the first four letters. In the following example you will see the getline function used with an array.

Example 2.7
Step 1: Write the following code into your favorite text editor.

#include <iostream>
using std::cin;
using std::cout;
int main()
{
char text[10];
cout << "Please enter a word\n";
cin.getline(text,10);
cout << text << endl;
return 0;
}
Step 2: Compile and run the program.

Step 3: Type in more than 10 characters. You should see something like what is
s42000 4:44 PM - 10 November, 2006
depicted in Figure 2.7.


Figure 2.7: The getline function.
You should notice that only 10 characters are placed in the character array, no matter how many you enter. In fact, you should probably prove this to yourself by deliberately typing in more text. This means that getline is the safe choice if you want to enter a string of characters into an array.


Using the Standard Namespace
Namespaces allow C++ programmers to group a set of global objects or functions under a single name. The general format of a namespaces is the following.

namespace identifier
{
namespace-body
}
The word identifier represents any valid identifier and namespace-body is the set of objects or functions that is included within the namespace. An example follows.

namespace mynamespace
{
int a, b;
}

In the code segment shown here, a and b are normal variables integrated within the namespace named mynamespace. To access these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:

mynamespace::a
mynamespace::b
The use of namespaces is particularly handy in cases where there is a possibility that a global object or function can have the same name as some other object or function. Using namespaces allows you to specify which one you are referring to. Let’s look at a code segment that shows how namespaces can help with cases where two variables have the same name.

#include <iostream>
using std::cout;
using std::endl;
namespace nameone
{
int myvar = 5;
}
namespace nametwo
{
float myvar = 9.6f;
}
int main () {
cout << nameone::myvar << endl;
cout << nametwo::myvar << endl;

return 0;
}
Hint! After the 9.6, there is a small lowercase letter f. This is to denote that this number is a float. If you do not put that there, many C++ compilers will assume that it is a double.


Without the use of namespaces you would get an error trying to use two variables with the same name.

The most common use of namespaces, is by far with the standard namespace. When you include iostream you have been identifying each item you wish use. However, you don’t have to do that if you simply specify that you are using the standard namespace. The following is code snippet that includes the standard namespace.

#include <iostream>
using namespace std;
You use namespaces by simply executing the following statement.

using namespace namespacename;
Now you can access the elements contained in that namespace simply by calling their names. It’s a little like using the include statements we have already seen in this chapter.

// using namespace example
#include <iostream>
namespace nameone
{
int myvar = 5;
}
namespace nametwo
{
float myvar = 9.6f;
}
int main ()
{
using namespace nametwo;
cout << myvar << endl;
return 0;
}
In this case, because you stated explicitly that you were using namespace nametwo, whenever you reference the variable myvar, it will be the version contained in namespace nametwo.

You may be asking what this has to do with console input and output, and that’s a good question. This topic is covered here because the standard namespace is what allows you to use names such as cout, cin , and endl. Visual C++ will allow you to use the .h extensions and not include the standard namespace. However this is not standard and not widely supported, so you will normally need to include the namespace. In fact, it’s best to just use the ANSI/ISO standards wherever possible because these standards are supported by ALL C++ compilers. This book uses only ANSI/ISO standard C++, with a few minor exceptions, which are noted in the text. With all of that said, you should plan on using the ANSI/ISO standard way of including the iostream header file.

#include <iostream>
using namespace std ;


Additional Formatting
There are other ways of formatting text, other than the escape characters. Many of these are new to C++ and are not supported in C. In addition to formatting, your C++ compiler can also convert values of various types into characters. You can control formatting with certain C++ commands such as the following:

cout << endl;—Newline.

cout << flush;—Flush buffer.

cout << hex;—Base 16.

cout << dec;—Base 10.

cout << setprecision(5);—Sets floating point format.

fill(x)—Pad fields with the x character. (You can use any character you wish.)

width(i)—Sets the field width to the value represented by the integer i.

precision(i)—Sets the number of significant digits displayed in floating point numbers.

setf(ios::flagname)—Sets the various flags mentioned in the following section. You call the setf function and pass to it the word ios:: followed by the actual flag you wish to set.

The following items are flags, rather than functions. A flag is a preset value that is used to determine a course of action. Flags are normally integer values, but often are given a name, or label, to make their value more readily apparent to human programmers. In this case, the flags determine how the setf function will format the output. This means that you simply set them to some value rather than call them, or pass them, parameters.

Floatfield—A flag to set the style for floating point numbers: scientific (exponential notation) or fixed

Scientific—A flag to set the style for scientific notation

Adjustfield—A flag to set alignment in fields such as left or right aligned

This next example illustrates several of the various formatting functions and properties that we have just discussed. This should allow you to see these items in action and get a much better feel for them.

Example 2.8
Step 1: Type the following code into your favorite text editor.

#include <iostream>
#include <iomanip> // This header file is required for
// the setprecision manipulator
using namespace std; // this is a shortcut. Instead of
// including each item in the std
// namespace, just include them
// all!
int main()
{
cout << 2002 <<endl;
cout << "In hex " << hex<< 2002 <<endl;
cout.setf(ios::scientific,ios::floatfield);
cout <<987.123456 <<endl;
cout << setprecision(3) << 987.123456 <<endl;
cout.fill('X');
cout.width(10);
cout << 1234 <<endl;
cout.setf(ios::left,ios::adjustfield);
cout.width(10);
cout << 1234 <<endl;
return 0;
}
Step 2: Compile your code.

Step 3: Run the executable. You should see something similar to the image shown in Figure 2.8.


Figure 2.8: Formatting.
This section is meant to introduce you to these formatting techniques. You will see many of them used again throughout the book, so you will get a chance to get more comfortable with them as we go.

Character Arrays
One of the most common uses of an array is a character array. A character array is simply a string of characters that makes up one or more words. It is common to place such input into arrays of characters. Let’s look at two examples.

Example 3.4
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
using namespace std;
int main()
{

char name[25];
cout << "Please enter your name \n";
cin >> name;
cout << "Hello " << name << endl;
return 0;
}
Step 2: Compile and run the program. You should see something similar to what is shown in Figure 3.3.


Figure 3.3: Character arrays.
This code is a rather straightforward and practical illustration of how to use arrays, specifically arrays of characters. There is only one problem. We declared the array to hold 25 characters. What happens if the user enters 30 characters? The answer is that your program may crash. However, there is a solution. In Chapter 2 you were introduced to the getline function and you were told that it was the safest way to input data into an array. Recall that the getline function specified what array to put the address in, and how many bytes to put in. If the user enters more data than that, then the extra characters are simply ignored.

Example 3.5
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
using namespace std;
int main()
{

char name[25];
cout << "Please enter your name \n";
cin.getline(name,25);
cout << "Hello " << name << endl;
return 0;
}
Step 2: Compile and run the code. You should see something similar to Figure 3.4.


Figure 3.4: Using getline with character arrays.


Using and Formatting Strings
You have already seen several different variable types and we have used them for input and output. There is another type of variable we have not used yet. This is the string variable. A string is essentially a bunch of characters all together that you can use to store text. Up to this point we simply used an array of characters. You can still do this, but now you have other options. Now, C++ has a string variable that you can use. To use the string variable you will have to include the string header file. Here is an example.

Example 3.6
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
#include <string>
using namespace std ;
using std::cout;
using std::cin;
int main()
{
string s = "C++ is sooo coool! \n";
cout <<s;
return 0;
}
Step 2: Compile and run the program. You will see something similar to what is shown in Figure 3.5.


Figure 3.5: The C++ string.
When you run this you will see how the string variable works. Essentially it is an open-ended character array you can use to store string data.

With C++, your string functions are defined in the string header file. Each string is an object that has methods and properties that you can use. Objects and classes will be covered in Chapter 10. For now, remember that an object is a special type of variable that has functions associated with it. These functions are called methods. The length property is a commonly used property of strings, which is easy to implement and understand.

Example 3.7
Step 1:

#include <iostream>
#include <string> // include for C++ standard string
// class
using namespace std;
int main()
{
string stringA = "C++";
string stringB = "Is Cool";
cout << "Length of stringA = " << stringA.length() <<
endl;
cout << "Length of stringB = " << stringB.length() <<
endl;
return 0;
}
Step 2: When you run this code you should see something similar to what is shown in Figure 3.6.


Figure 3.6: String operations.
You can see that, in C++, the string is an object with properties and methods. There are a number of properties and methods with this object; the most commonly used are summarized in Table 3.2.

Table 3.2: Properties and Methods of the String Class Property/Method
Purpose

Length
Property that returns the length of the string.

Copy
This copies from one string to another.

Erase
This method erases the string.

Insert
This inserts a set of characters into a string.


Most C++ compilers still support C header files, and C functions. These C-style string functions are still used frequently. Therefore, a summary of some of these functions and an example are included here. The more important and commonly used functions from string.h are summarized in Table 3.3.

Table 3.3: String Functions Function
Purpose
Format

strcpy
To copy one string to another.
char * strcpy (char * dest, const char * src);

Note: The * is a special operator that will be explained in detail in the chapter on pointers.

strlen
To return the length of a string.
size_t strlen ( const char * string);

strncat
Append a sub string onto another string.
char * strncat (char * dest, const char * src, sizet_t num);

strstr
Find one string inside of another string.
char * strstr (const char * string1, const char * string2);


There are several other functions in the string header file, but these are the most commonly used functions. The following example illustrates the use of these functions.

Example 3.8
Step 1:

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

int main()
{
char firststring[40],secondstring[40],thirdstring[40];
int size;
cout << "Please enter a word \n";
cin.getline(firststring,40);
cout << "Please enter another word \n";
cin.getline(secondstring,40);
size = strlen(firststring);

strcat(firststring,secondstring);
cout << "The length of the first string you entered
is" << size << "\n";
cout << "Both strings you entered are " <<
thirdstring<< "\n";
return 0;
}
This example, although simple, should show you how to use some of the functions you will find in the string header file.

Hint! The previous example is using C-styled string manipulations. This is actually supported by many of the commonly used C++ compilers.

Bitwise Operations
The bitwise operators are a bit more difficult to understand than standard operators (pun intended). The first order of business is to define what a bit is. The computer ultimately stores everything as either a 1 or a 0. A single value of either 1 or 0 is called a bit. Essentially C++ allows you to work directly with the binary equivalents of numbers, to work with bits. This is useful in many computer applications, especially in the telecommunications industry. You will also see these operations in a later chapter when we explore basic encryption algorithms. Explaining bitwise operations necessitates first explaining binary numbers.

The numbers you are familiar with in day to day usage are decimal numbers, base 10 numbers. The base 10 number system is only one possible number system. You can use base 2, base 5, base 16, or any other base you wish. The reason most human societies have always used base 10 number systems is that we have ten fingers. Therefore, our ancestors had an easier time counting in tens, thus number systems started out being based on 10. A computer, however, “speaks” in on or off, base 2 numbers (also called binary numbers). For this reason a basic understanding of binary numbers is essential for programming. In the base 2 number system you can only have 0’s and 1’s. (Notice you don’t actually have any 2’s, just as the base 10 system only has 0’s to 9’s.) What this means is that after you have placed a zero or a one in a particular place, to increase the number you have to move over to a new place. This table (Table 3.4) might help clarify that a bit.

Table 3.4: Binary Numbers Base 10 Number
Base 2 Equivalent

0
0

1
1

2
10 (Note this is a 1 in the 2’s place and a 0 in the 1’s place, or one 2 and no 1’s.)

3
11 (This is a 1 in the 2’s place and a 1 in the 1’s place, thus equaling one 2 and one 1, which is 3.)

4
100 (This is a 1 in the 4’s place, a 0 in the 2’s place, and a 0 in the 1’s place.)

5
101 (This is a 1 in the 4’s place, a 0 in the 2’s place, and a 1 in the 1’s place.)

6
110 (This is a 1 in the 4’s place, a 1 in the 2’s place, and a 0 in the 1’s place.)

7
111 (This is a 1 in the 4’s place, a 1 in the 2’s place, and a 1 in the 1’s place. And 4 plus 2 plus 1 equals 7.)

8
1000 (This is a 1 in the 8’s place with a 0 in the 4’s, 2’s, and 1’s places.)


Hopefully you are noticing a pattern here. The places in any number system are essentially the number system’s base raised to some power. For example, in the base 10 system you have a 1’s place, 10’s place, 100’s place, 1000’s place, and so on. If you think about this for just a moment you should realize that 1 is simply 100, 10 is 101, 100 is 102, 1000 is 103, and so on. The same is true for the base 2 number system, where you have a 1’s place, 2’s place, 4’s place, 8’s place, 16’s place, and so on. 1 is simply 20, 2 is 21, 4 is 22, 8 is 23, 16 is 24, 32 is 25 and so forth.

In computers everything is stored in groups of eight bits, called bytes. For this reason all binary numbers are actually represented by an eight-digit series of bits. So that one is represented as 00000001, two as 00000010, three as 00000011, and so on.

Now that you have a basic understanding of what binary numbers are, we can explore bitwise operators. Bitwise operators work on integers as if they where binary numbers. Let’s examine the bitwise shift operators first. A bitwise left shift literally shifts all the bits to the left the specified number of places. Consider the following shift operation.

4 << 1
This means to take the binary equivalent of 4 (which is 00001000) and shift all the bits over 1 space. This makes the number 00010000. Notice that this shifts it over to an entirely new place, the 8’s place. So operation 4 <<1 actually yields 8. The right shift operator (>>) simply shifts the numbers to the right rather than the left.

The other two bitwise operators (& and |) are of particular use in a variety of applications including such diverse areas as Windows programming, telecommunication, and encryption, as you will see later in this book. The & operators simply asks whether the digits in both numbers are a 1 (and not a 0). For example, 4 & 2 would actually be evaluated in binary as 00001000 & 00000010; to see how this works, compare them vertically.

00001000
00000010
You can now see that this would yield 00000000, because in neither case do both numbers have a 1 in the same place. To further clarify this point, let’s compare two other numbers, 5 & 3. In binary this would be the following.

00001001
00000011
This would yield 00000001 because only in the final place do the two numbers have a 1 in the same place.

The | (or) operator asks whether either number has a 1 in that particular place. So if you compare 5 | 3 you would have the following.

00001001
00000011

And that would yield 00001011 (which is 7 in decimal numbers).

The ^ operator is called the exclusive or, or XOR operator. It asks if there is a 1 in one of the numbers but not both, at a given place. For example if you consider 7 and 4 and you XOR them you see the following.

00000111
00000100
You get 00000011 or 3 because the XOR operation asks if there is a 1 in the place of one number but NOT the other. In other words, the XOR operation is exclusive to one or the other number, but not both, thus the name. The following example will allow you to AND, OR, and XOR integers.

Example 3.9
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
using namespace std;
int main()
{

int num1, num2,iand,ior,ixor;
cout << "Enter an integer \n";
cin >> num1;
cout << "Enter another integer \n";
cin >> num2;
iand = num1 & num2;
ior = num1 | num2;
ixor = num1 ^ num2;

cout << num1 << " AND " << num2 << " is " << iand <<
endl;
cout << num1 << " OR " << num2 << " is " << ior <<
endl;
cout << num1 << " XOR " << num2 << " is " << ixor <<
endl;
return 0;
}
Step 2: Compile and run the code. You should see an image much like the one shown in Figure 3.7.


Figure 3.7: Bitwise operations.
These binary operators are going to be of particular importance to you later when you encounter encryption, but they are also used in other types of programming. It is also important to understand binary numbers for the simple reason that this is what the computer ultimately translates everything you enter into. The computer only understands binary numbers, so anything you enter into it gets translated into binary.


Creating and Calling Functions
Obviously you could simply put everything into the main function and it would, indeed, compile and run, but this would quickly become unwieldy. In fact, your program would certainly become completely unmanageable and unreadable by the time it even reached a few dozen lines of code. Fortunately you don’t have to do that. You can create separate functions to handle these other items. There are a few idiosyncrasies regarding function creation in C++. The following list summarizes the requirements.

The function must have a return type. It may be void if the function returns nothing.

The function must have a valid name.

The function must have parentheses for a list of parameters past to it, even if the parentheses are empty.

The function must either be written before it’s called, or it must be prototyped.

The first three you already know about, but the fourth rule may sound quite confusing. What does it mean to prototype a function? Essentially the problem is that the C++ compiler cannot call a function it does not know about. You have to let the compiler know what that function is and what it does before you can call it. One way to do this is to make sure you write out the function in your file, before you call it. This quickly becomes quite cumbersome. Therefore, C++ provides another way to do this. That method is prototyping. All you do to prototype a function is to write its declaration line at the beginning of the source file. This would probably be much clearer with an example.

Example 4.1
In this example we will create a function that simply cubes any number passed to it and returns the answer. That function is prototyped and then called from the main function.

Step 1: Open your favorite text editor and type in the following code. You will then save it to a file called 04-01.cpp.

// Include statements
#include <iostream>
using namespace std;
// function prototypes.
float cube_number(float num);
int main()
{
float number;
float number4;
cout << "Please enter a number \n";
cin >> number;

number4 = cube_number(number);
cout << number << " cubed is " << number4;
return 0;
}
float cube_number(float num)
{
// this function simply takes a number, cubes it,
// then returns the answer
float answer;
return answer;
}
Step 2: Compile the code. (See Appendix D if you need more instruction on how to compile your programs.)

Step 3: You can now run your program by typing in 04-01 at the command prompt. If all goes well (no compile errors), then you will see something like what is shown in Figure 4.1.


Figure 4.1: Basic functions.
This code contains the essentials of writing, prototyping, and using functions. Let’s examine it piece by piece to make sure you understand what is happening. The first line is simply an include statement. We include the iostream header file, so that you can do input and output (as you first saw in Chapter 2). The second line identifies that we wish to use the standard namespace, thus giving us access to cout, cin, endl, and any other function that may reside in iostream. Next is our prototype for our function. It is literally an exact copy of that functions declaration line. It lets the compiler know that there is a function later in the code. It’s defined so that it takes certain parameters and returns a certain value. (If you see a call to this function, before you get to the part where the function is written, don’t panic!).

Hint! The main function does not need to be prototyped; its declaration line is built into C++. Also, functions that are included in one of the C++ header files do not need to be prototyped (such as cin and strcpy from Chapter 2).


Once you get into the main function of this program, you see a few variables declared. One variable, number, stores whatever number the user types in. The second variable, number4, is designed to store the answer that the cube_number function returns. When you call cube_number, because it returns a value, you must set the function on the righthand side of an equation with an appropriate variable. The following is a generic example. Some variable, of the same data type as the function’s return type, is set equal to the function name. For example, float:

f = myfunc()
This example uses a variable of type double (the same type as the function is declared to return) and sets that variable equal to that function. This expression will cause the function to be called and its value stored in the variable in question.

You should also pay particular attention to the function cube_number. Notice that it does have a parameter. Beginning programmers sometimes have trouble understanding what to pass as a parameter. The simple rule of thumb is this: If you were going to ask some person to perform the same task you are asking the function to perform, what would you have to give them? The answer to that is the parameters you will need to pass to the function in question. If you were asked to cube a number, someone would have to give you the number to cube. Thus, if you ask a function to cube a number, you have to pass it that number. Parameters are simply values stored in variables that you pass to functions. They are the raw “stuff” that functions use to produce the product desired. Parameters are also frequently called “arguments.” The words argument and parameter are used interchangeably.

Let’s take a look at another example.

Example 4.2
In this example, the function takes two parameters to compute the area of a triangle. The formula for this is area = 1/2 of the base of the triangle, multiplied by the height of the triangle.

A = 1/2 (b * h)
Step 1: Enter the following code in your favorite text editor. Save it in a file called 04-02.cpp.

#include <iostream>
using namespace std;
// function prototypes
float triangle_area(float b, float h);
int main()
{
float base, height, area;
// get the user input
cout << "Please enter the base of the triangle
\n";
cin>> base;
cout << "Please enter the height of the
triangle\n";
cin >> height;
area = triangle_area(base , height);
cout << "That triangles area is " << area;
return 0;
}
float triangle_area(float b, float h)
{
float a;
a = .5 * (b * h);
return a;
}
Step 2: Compile the code.

Step 3: Run the code. You should see something similar to what is presented in Figure 4.2.


Figure 4.2: Basic functions 2.
This example is a lot like the first example, with the exception that the function triangle_area takes two parameters. A function may take zero parameters, one parameter, two parameters, and so on. Theoretically you can have a long list of parameters (also called arguments), dozens if you wish. However, as a rule of thumb, if you need more than three or four parameters, you may wish to rethink your code.

You should note that with the exception of the two parameters instead of one, this program is very much like the first one. It begins with include statements, prototypes any functions other than main, has the main function, and then has other functions. You don’t have to declare the main function first. However, it seems logical to put that function first, because that is where the entire program is going to start. Also remember that you can have a function call another function. In fact, in both of our examples, the main function called the second function.


Function Overloading
C++ provides you with a powerful tool—overloading. You can overload a function so that the same name is shared by more than one function, but each function performs a different action. Function overloading is essentially when you have more than one function with the same name, but each performs different arguments. The first question that comes to your mind is probably: Why would you want to overload a function? There are several cases in which you may want to do this. For example, if you wanted to do an operation on some input, but the input came in different forms. The input might be an integer value or a floating point decimal value. You could overload the function in question, and have one version take an integer argument and the other a float argument. Let’s take a second look at our number cubed example to illustrate this.

Example 4.3
Step 1: Open your favorite text editor and type in the following code. Save the code as 04-03.cpp.

// Include statements
#include <iostream>
using namespace std;
// function prototypes.
float cube_number(float num);
int cube_number(int num);
int main()
{
float number;
float number4;

cout << "Please enter a number \n";
cin >> number;
number4 = cube_number(number);
cout << number << " cubed is " << number4;
return 0;
}
int cube_number(int num)
{
int answer;
answer = num * num * num;
return answer;
}
float cube_number(float num)
{
float answer;
answer = num * num * num;
return answer;
}
Step 2: Compile your code.

Step 3: Execute the code. You should see something like the image shown in Figure 4.3.


Figure 4.3: Function overloading.
Notice that there are two functions named cube_number. They both take a single argument and return that argument cubed. However, the first function takes an integer and returns an integer answer, whereas the second function takes a floating point number and returns a floating point answer. The big question is how does the compiler know which function you are calling? The answer is simple, it knows which function you are calling based on what kind of argument you pass it. If you pass an argument with a decimal point, then it will call the function that takes a floating decimal point. If you pass an argument without a decimal point, then it will call the function that takes an integer.

This is why all overloaded functions MUST have different parameter types and/or a different number of parameters. You will see examples with different numbers of parameters later in this book.




Header Files
So far we have only used header files that were built into C++. We have not used any files that we created. This section will change all of that. Header files are used to contain the prototypes for a function. (Other things can be placed in them, as we will see later in this book.). All you need to do is open your favorite text editor and place the prototype lines in that editor, then save the file with an .h extension.

Example 4.4
This example will show you how to create and how to use header files for function prototypes.

Step 1: Open your favorite text editor and type in the following code.

// function prototypes.
float cube_number(float num);
int cube_number(int num);

Save this file as test.h.

Step 2: Open a new instance of your favorite text editor and type the following code.

// Include statements
#include <test.h>
#include <iostream>
using namespace std;
int main()
{
float number;
float number4;
cout << "Please enter a number \n:’
cin >> number;
number4 = cube_number(number);
cout << number << " cubed is " << number4;
return 1;
}
int cube_number(int num)
{
int answer;
answer = num * num * num;
return answer;
}
float cube_number(float num)
{
float answer;
answer = num * num * num;
return answer;
}
Step 3: Compile your code.

Step 4: When you run your code, you should see something like Figure 4.4.


Figure 4.4: Header files.
This is a simplified example, but it does illustrate the basic points. Usually the actual functions would also be in a different file, if you were using a header file. However, in this case the purpose was to introduce you to creating your own header files.

Passing Values by Reference
When you pass a value to a function you are really copying the contents of one variable to another variable—the other variable is the parameter of a function. This means the parameter is, essentially, a copy of the variable that was passed to the function. This means that you are not changing the value of the variable that is outside the function. That might sound confusing, so let’s look at an example that illustrates this concept.

Example 4.5
Step 1: Place the following code into your favorite text editor.

#include <iostream>
using namespace std;
void demo(float);
int main ()
{
float num1;
cout << "Please enter a number. \n";
cin >> num1;
cout << "Before the demo function your number is "
<< num1 << "\n";
demo(num1);
cout << "After the demo function your number is
still" << num1 << "\n";
return 0;
}
void demo(float number)
{
number = number * 4;
cout << "Inside the demo function the number is now
" << number << "\n";
}
Step 2: Compile this code.

Step 3: Run the code. You should see something similar to the image shown in Figure 4.5.


Figure 4.5: Passing variables.
As you can see from this example, what occurs inside the function has no bearing on the values of the variables outside the program. When you call the demo function, you take the value that is in num1 and place that value in the function parameter number. Number is an entirely new variable occupying its own space in memory and is separate from num1. This is called passing a variable by value. It is the standard way that variables are passed in C++ (as well as in Java and several other languages).

There is another way to pass a variable. That is by reference. When you pass by reference you don’t simply copy the value of some variable to a parameter. What you pass is a reference to the variable’s address in memory. What that means is that the parameter of the function is NOT a new variable. It is simply a new name for the variable. Both the variable name and the parameter name refer to the same place in memory, they refer to the same value. You accomplish this by simply adding the & or address of operator to your function parameter. The & means address of and it refers to the address in memory. Let’s look at the previous example redone to pass-by reference.

Example 4.6
Step 1: Write the following code in your favorite text editor.

#include <iostream>
using namespace std;
void demo(float &number);
int main ()
{
float num1;
cout << "Please enter a number. \n";
cin >> num1;
cout << "Before the demo function your number is "
<< num1 << "\n";
demo(num1);
cout << "After the demo function your number is"
<< num1 << "\n";
return 0;
}
void demo(float &number)
{
number = number * 4;
cout << "Inside the demo function the number is now
<DS>" << number << "\n";
}
Step 2: Compile the code.

Step 3: Run the code. You should see something like what is shown in Figure 4.6.


Figure 4.6: Passing with the & operator.
Notice that this time when the value is changed inside the function, it is also changed in the variable outside the function. This is because you passed the address of that variable to the function. The parameter name was just an alias for the variable. Whatever you did inside the function was actually happening to the variable.

Built-in Functions
In addition to the various functions you can create, C++ includes some useful functions you can use. Actually the term built-in is not exactly accurate, but it is close enough. These are functions that can be included in your program and then use. In fact, there are quite a few such functions. This book will show you some of the most commonly used functions and also show you some examples of how to use these functions. A few of the more commonly used functions are summarized in Table 4.1.

Table 4.1: C++ Functions Function
Purpose

void *memcpy(*destination, *source, size);
This function copies whatever is in the source (often an array or structure [see Chapter 8]) to the destination. The size tells you how much to copy. To use this function you must either include the memory or string header files.

void * memset(*destination, replacement, size)
This function sets the destination to the character shown in replacement. This is often used to set an array to all zeros. To use this function you must either include the memory or string header files.

char* itoa( int value, char* buffer, int radix ) Note: This one is NOT ANSI Standard C++ but is quite commonly used and supported by most C++ compilers.
This takes an integer and returns the character equivalent. The radix is the base of the integer you are converting it from (base 2, base 10, etc.).

int atoi( const char *string);
This function takes a character and returns the integer equivalent.

int tolower( int c );
Converts the character to lowercase. You must include the string header file for this function.

int toupper( int c );
Converts the character to uppercase. You must include the string header file for this function.

Hint! memcpy and memset are frequently used with structures, which will be described in detail in Chapter 8. They can, however, also be used with arrays, which were introduced in Chapter 3.


The memcpy function shown in Table 4.1 is used to copy complex data types, such as arrays and structures, from one location in memory to another. You cannot simply copy one array to another as you would copy a standard variable. The following is an example.

int x,y;
x = 4
y = x

This works fine, and the contents of x are copied to y. However, this does not work with arrays.

int x[10] = {2,4,1,6,6,9,0,11,1,2};
int y[10];
y = x;
This will not work. It will generate a compiler error. So how do you copy one array to another? That is where memcpy comes in. To use memcpy, you must first include the memory header file.

#include <iostream>
#include <memory>
using namespace std;
int main()
{
int x[10] = {1,2,3,4,5,6,7,8,9,0};
int y[10];
memcpy(y,x,10);
return 0;
}
The function copies items from the second parameter to the first parameter, from the source to the destination. It copies the number of bytes you indicate in the third parameter, the size parameter. You will find these functions, and others, used throughout this text, and in many other C++ books. Let’s take a look at an example that uses a few of these.

Example 4.7
Step 1: Type the following code into your favorite text editor.

#include <iostream>
using namespace std;
int main()
{
char a,u,l;
int x;
cout << "Please enter a number \n";
cin >> a;
x = atoi(&a);
cout << "The character " << a << " is converted to
the integer " << x << "\n";
cout << "Please enter a character \n";
cin >> a;
u = toupper(a);
l = tolower(a);

cout << a << " in upper case is " << u << " in
lower case is " << l;
cout << "\n Press a key to continue ";
return 0;
}
Step 2: Compile the code.

Step 3: Run the code. You should see something similar to what is shown in Figure 4.7.


Figure 4.7: Assorted functions.
Hint! The & operator is used with the itoa function. This is the addressof operator and means that we are passing the address of the variable rather than the actual value contained in the variable.


The previous example illustrated the most commonly encountered of C++’s built-in functions. These functions will be quite useful to you as you continue through this book. Several of them will be used in later chapters. It would be well worth your time to ensure that you are well-acquainted with each of these functions.



Math Operations
C++ has a rich set of mathematical operations that are at your disposal. Learning to use these will be quite useful to you as we move throughout this book. To utilize these functions you need to include the math header file.

#include <cmath>
This header file includes a lot of math functions that are very useful. The most commonly used functions are listed in Table 4.2.

Table 4.2: Math Functions Function
Purpose

double cos(double);
This function takes an angle (as a double) and returns the cosine.

double sin(double);
This function takes an angle (as a double) and returns the sine.

double tan(double);
This function takes an angle (as a double) and returns the tangent.

double log(double);
This function takes a number and returns the natural log of that number.

double pow(double, double);
With this function, you pass it two numbers. The first is a number you wish to raise and the second is the power you wish to raise it to.

double hypot(double, double);
If you pass this function the length of two sides of a right triangle, it will return you the length of the hypotenuse.

double sqrt(double);
You pass this function a number and it gives you this square root.

int abs(int);
This function returns the absolute value of an integer that is passed to it.

double fabs(double)
This function returns the absolute value of any decimal number passed to it.

double floor(double)
Finds the integer which is less than or equal to the argument passed to it.

Hint! In this table you probably noticed that the function arguments are listed only as types, with no name. When you call the functions you will pass it the name of whatever variable you wish to pass it. What that function internally calls the argument is irrelevant. What is important is remembering what type to pass it and what type it will return.


There are many other math functions available to you when you include this header file, but the functions shown in Table 4.2 are the most commonly used. The following example illustrates some of these functions.

Example 4.8
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
#include <cmath>//Math.h is the old C style math
//header file
using namespace std;
int main()
{
double angle, dsine,dcos,dtan;
cout << "Please enter an angle in radians \n";
cin >> angle;
dcos =cos(angle);
dsine =sin(angle);
dtan =tan(angle);
cout << " Your angles trigonometric functions are
\n";
cout << " Sine is " << dsine << "\n";
cout << " Cosine is " << dcos << "\n";
cout << " Tangent is " << dtan << "\n";
return 0;
}// main
Step 2: Compile the code.

Step 3: When you run the code you should see something like what is shown in Figure 4.8.


Figure 4.8: Math functions.
You can see that trigonometry is quite easy with C++ math functions. Although not covered here, that math.h header file also has hyperbolic trigonometric functions and arc functions.

In addition to trigonometry functions, you have a number of standard math functions at your disposal. You should have noticed some of these listed in Table 4.2. The following example illustrates some of these functions.

Example 4.9
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double number, dsqrt,dpow,dlog;
cout << "Please enter a number \n";
cin >> number;
dsqrt =sqrt(number);
dpow =pow(number,5);
dlog =log(number);
cout << " Math Example\n";
cout << " Square Root is " << dsqrt << "\n";
cout << " Raised to the fifth power is " << dpow <<
"\n";
cout << " Log is " << dlog << "\n";
return 0;
}// main
Step 2: Compile the code.

Step 3: Run the code. You should see something similar to the image in Figure 4.9.


Figure 4.9: More math functions.
As you can see, most mathematics is quite simple using C++. It is not uncommon to find that mathematicians who take up programming as a hobby often choose C++ as their language of choice. Chapter 3 demonstrated how easily C++ handles binary numbers, and now you have seen that it has a number of math functions already defined.

Time
It is common for programmers to need to get the time for some reason or another. You might simply wish to display the current time to the user, timestamp a file, or check to see if the current time is within some range of dates. C++ provides you with a rich set of tools to do this. You simply need to include the ctime header file and you can access these functions and objects (see Table 4.3).

Table 4.3: Time Functions Found in Ctime Function
Purpose

time_t time ( time_t * timer );
Gets the number of seconds elapsed since 00:00 hours, Jan 1, 1970

UTC from the system clock.

struct tm * localtime (const time_t * timer );
Converts timer to tm structure, adjusting to the local time zone.

double difftime (time_t timer2, time_t timer1 );
Calculates the time difference between timer1 and timer2 in seconds.

struct tm * gmtime (const time_t * timer );
Converts timer to tm structure, adjusting to GMT time zone.

char * ctime (const time_t * timer );
Converts time to a string containing time and date adjusted to local time zone in readable format. This is usually used to present the time in a more readable format.


This is not an exhaustive list, but it does show you the most important functions found in the ctime header file. This might be even clearer for you if you saw an example of this in action. With that in mind, please consider the following example.

Example 4.10
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
#include <ctime>
using namespace std;
int main ()
{
time_t rawtime;
time ( &rawtime );
cout << "Current date and time is: "<< ctime
(&rawtime);
return 0;
}

Step 2: Compile the code and run it. You should see something like what is depicted in Figure 4.10.


Figure 4.10: Using time functions.
Hint! The C method was to include <time.h> and you may still see this occasionally. Most of the functions are the same, at least calling them is the same.


Random Numbers
There are many cases where you will wish to generate a random number. If you wished to generate a random number to use as an encryption key, or if you needed random numbers for a game, you would require some function that generates a random number for you.

There are actually two functions you will need to know about. The first is rand(). This function will only return a pseudo random number. The way to fix this is to first call the srand() function. That function seeds the rand() function with a truly random number to start it off. Usually you use the time function to get the number of seconds on your system time, to randomly seed the rand() function. The following example demonstrates this.

Example 4.11
Step 1: Place the following code in your favorite text editor.

#include <iostream>
#include <ctime>
using namespace std;
void main( void )
{
int i,j;
srand( (unsigned)time( NULL ) );
/* Display 10 numbers. */
for( i = 0;i < 10;i++ )
{
j= rand();
cout << j << endl;
}
}
Step 2: Compile and execute the code. You should see something like what is depicted in Figure 4.11


Figure 4.11: Using the random functions.
The most important thing to remember is that you must use the srand() function to seed the random function or you will not get truly random numbers. Later in this text when we develop a simple game, you will see the random function used.


Chapter 5: Decision Structures and Loops
Download CD Content
By now you should have a firm grasp of essentially what C++ is, and know how to create a variable, use functions, and write some simple C++ programs. Now it’s time to add to that knowledge, and expand your programming skill-set. This chapter will introduce you to decision structures and loops. These are key concepts that exist in all programming languages; it is just their implementation that is somewhat different. In this chapter, you will learn how to have your code branch in different directions based on certain criteria. You will also learn how to have your code loop repeatedly. A decision structure is a block of code that branches, depending on some decision. There are many times when you will need different code to execute, depending on some criteria such as user input. You have probably used programs in which you were asked to provide some input, maybe a simple yes or no. The program behaved differently based on the input you gave it. This is an example of a decision structure. Different blocks of code are executed differently based on some criteria. Essentially a decision structure is code that lets your code branch based on some criteria.

Most programs are simply combinations of decisions. If the user does this, then the program responds with one action. If the user does something else, then the program responds with a different action. The entire activity of data processing is dominated by decisions. For this reason, decision structures are a key programming concept found in all programming languages.

If Statements
The most common type of decision structure is the if statement. These exist in all programming languages but are implemented slightly differently. An if statement literally says, “if some condition exists, then do this certain code.” A generic, programming-language-neutral example would be the following.

If some condition exists
Execute this code
The condition is usually the value of some variable. If a particular variable contains a certain value, or even a range of values, then execute a given block of code. The diagram shown in Figure 5.1A shows the basic structure and flow of an if statement.


Figure 5.1A: The structure of an if statement.
It is important to recall that if statements are a common facet of almost all programming languages. In every case they will follow the structure and flow shown in Figure 5.1A, but the specific way a particular programming language might go about implementing this concept can be quite different from other languages. However, you should know that many languages use syntax that is similar to the syntax of C++. In fact, if statements in C, Java, and JavaScript are almost indistinguishable from if statements in C++. This is important for you to realize. The more thoroughly you master the C++ programming language, the easier it will be for you to learn these other programming languages at some future data, should you so desire.

Let’s look at how you implement if statements in C++. Here is a basic example that we can dissect to help you learn about if statements.

If( age == 16)
{
cout << "Yahoo... Your old enough to drive!\n";
}
Let’s take a look at this code because there are several things you should note. First of all, you have the word if followed by parentheses. Inside the parentheses is where you locate the condition that you base your if-statement on. In other words, if (whatever is in the parentheses is true) do the stuff in the following brackets. The brackets, recall from our discussion of functions, are just boundaries around any block of code. The code in these brackets is what you wish to execute if the statement in the parentheses is true. Finally, notice that there is a double equals sign in the parentheses. Think back to Chapter 1 where you were first introduced to operators. Remember that a single equals is an assignment operator and a double equals is an evaluation operator. By using the double equals, you are asking “is the age equal to 16?” If you used the single equals, you would be stating, “make the age equal to 16.”

Watchout! One of the most common mistakes that beginners make is to use a single equals (assignment operator) in an if statement rather than a double equals. If you use the single equals—the assignment operator instead of the double equals—the equality operator—you will make the if statement true every time.


Example 5.1
Let’s use an if statement in a simple program. What we are going to do is to use a simple menu displayed on the screen, and then proceed based on what the user selects.

Step 1: Type the following code into your favorite text editor. Save it as 05-01.cpp.

#include <iostream>
using namespace std;
float square_num(float num);
float cube_num(float num);
int main()
{
int choice;
float number, answer;
cout << "Would you like to (1) square a number or
(2)
cube a number\? \n";
cout << "Please press the number of your choice 1 or
2 \n";
cin >> choice;
cout << "Please enter your number \n";
cin >> number;
if (choice == 1 )
{
answer = square_num(number);
}
else
{
answer = cube_num(number);
}
cout << "Your answer is " << answer <<" \n";
return 0;
}
float square_num(float num)
{
float a;
a = num * num;
return a;
}

float cube_num(float num)
{
float a;
a = num * num * num;
return a;
}
Step 2: Compile your code.

Step 3: Run your code. You should see something like the image shown in Figure 5.1B.


Figure 5.1B: if Statements.
What you see here is the use of an if-else statement. If some condition is true, execute the first block of code. If that condition is not true, then execute the second block of code. This is a very common programming situation, and if statements exist in all programming languages, although their implementations may differ. if statements are a fundamental part of programming. Most programming tasks can, at some level, be reduced to “if some condition exists do this.”

It is possible to have if statements and else statements without enclosing the blocks of code with brackets, if and only if the code block consists of one line of code. Consider the following examples.

if(x == 7)
y++;

This is perfectly legal. The C++ compiler will assume that the very first line following the if statement is the block of code to execute, even without brackets. However the following code segment is not OK.

if (x==7)
y++;
z—;
In this case, only the first line, the y++, will be executed based on the if statement. The second line will not be considered part of the if statement code block. In other words, the second line is going to execute regardless of whether the if statement is true.

You should also note that although all these examples have used equivalence (if the variable equals some value), you can also use other comparisons, besides equivalence. You can use greater than and less than comparisons as well. The following code fragments are perfectly valid C++ if statements.

if (x > 6)
if (j < 10)
You can also use not equal, equal or greater than, and equal or less than as you see in the following examples.

if (x !=6)
if (j =< 10)
Other possibilities include ranges of values. For example, you may want to know if a particular variable is between two values such as in the following example.

if (5 < j < 10)
Asks if j is greater than 5 but less than 10. This particular situation is quite common.

if statements are also the most common place to see logical AND (&&) and logical OR (||) used.

If(j ==5 && I ==6)
… if(j < 4 || j> 10)

You should recall that the logical AND and logical OR were both briefly introduced in Chapter 1, in the section on operators. The following example shows the use of these operators in if statements.

Example 5.2
Step 1: Type the following code into your favorite text editor.

// Include statements
#include <iostream>
using namespace std;
float cube_number(float num);
float square_number(float num);
int main()
{
float number;
float number3;
cout << "Please enter a number \n";
cin >> number;

if (number > 0 && number < 100)
{
number3 = cube_number(number);
cout << number << "cubed is "<< number3;
}// end of if
else
{
number3 = square_number(number);
cout << number << "squared is "<< number3;
}// end of else
if (number3 <10000 || number3 ==2)
{
number3 = square_number(number3);
cout << number3 << "squared is "<< number3;
}// end of second if
return 0;
}// end of main
float square_number(float num)
{
float answer;
answer = num * num;
return answer;
}
float cube_number(float num)
{
float answer;
answer = num * num * num;
return answer;
}
Step 2: Compile the code.

You should see that you can easily use logical OR and logical AND in your if statements.

This gives you a versatile set of comparisons you can use in your code to create if statements. You will find, both in this book and in practical experience, that if statements are very common in most programming, regardless of the programming language used.

Another possible permutation of the if statement is the nested if statement. This is having one if statement inside another. This is not complicated, and if you indent your code properly it will be fairly easy to follow. The following is an example.

if (age >16)
{
if (validlicense == true)
{
cout << "Yes you can borrow the car \n";
}// end of the inner if
}// end of the outer if
The thing to realize about this code is that the inner if statement will never be checked if the outer if statement is false. This is an example of a nested if statement. One if statement is nested within another. You should be careful of nesting too many if statements. It eventually makes for code that is difficult to read and follow.


Switch Statements
if statements and if-else statements are great if you have one or two choices. But what happens when you have several choices? You can still use a series of if-else statements, but that quickly becomes cumbersome. Fortunately, there is another choice—the switch statement. A switch statement is literally saying, “switch the path you take through the code based on the value of some variable.” A switch can only be done on a single character or on an integer value. You can also think of a switch statement as a complex version of the if statement. It’s a way of using if statements when there are multiple possible choices. Switch statements, like if statements, exist in most programming languages and the structure is the same. The structure for a switch statement is shown in Figure 5.1C.


Figure 5.1C: Structure of a switch statement.
The implementation of the switch statement in C++ is relatively straightforward. Let’s take a look at an example in the following code segment.

int choice
switch (choice)
{
case 1:
cout << "You chose 1 \n";
break;
case 2:
cout << "You chose 2 \n";
break;
case 3:
cout << "You chose 3 \n";
break;
default:
cout << "You made an invalid choice \n";
break;
}
If you examine this code, you will notice several things. First, you will notice the brackets. The brackets start right after the switch statement and end after the last statement in the switch. A switch statement is a code block, just like an entire function or an if statement. And remember that all code blocks are bounded by brackets. You should also notice that each case has a number then a colon. What the code is literally saying is “if it is the case that the integer choice is equal to one, then execute this code.” At the end of each case, there is a break statement. This is very important. Without it, the code will continue to execute and will run the next case statement as well. Finally, we have a default statement. If the variable we are switching on does not match any of our cases, then the default will occur.

It is sometimes helpful to think of a switch statement like a switch on a railroad track. You will switch the direction you travel through the code, based on the value of the variable you have selected to base your switch on. Like if statements, the switch is common to most programming languages, just its implementation is different. Lets take a look at a program that uses a switch case statement to create a menu the user can select from. This program will also incorporate other concepts that we have already covered in this book.

Example 5.3a
Step 1: Open your favorite text editor and type in the following code, and save it as 05-03a.h.

void menu();
float circle_area(float);
float triangle_area(float, float);
float rectangle_area (float, float);
Step 2: Open your favorite text editor and type in the following code.

#include "05-03.h"
#include <iostream>
using namespace std;
int main()
{
// call the menu to cause it to display initially
menu();
return 0;
}// end of main function
void menu()
{
int menuchoice;
float radius, height, width, base, answer;
char somechar;
// This first section simply displays the users choices
// then
// prompts the user to make a selection.
cout << "1. Area of a circle \n";
cout << "2. Area of a triangle \n";
cout << "3. Area of a rectangle \n";
cout << "4. Exit \n";
cout << " \n Please enter the number of your selection
\n";
cin >> menuchoice; // whatever choice the user makes
// will be stored in the variable
// menuchoice
// This next section uses a switch case statement to
// determine the course of action
// based on what the user chose.
switch (menuchoice)
{
case 1: // area of circle
cout << "Please enter the radius of the
circle \n";
cin >> radius;
answer = circle_area(radius);
break;
case 2: //area of triangle
cout << "Please enter the base of the
triangle \n";
cin >> base;
cout << "Please enter the height of the
triangle \n";
cin >> height;
answer = triangle_area(base, height);
break;
case 3: // area of rectangle
cout << "Please enter the height of the
rectangle \n";
cin >> height;
cout << "Please enter the width of the
rectangle \n";
cin >> width;
answer = rectangle_area(height, width);
break;

case 4: // exit
return;
default:
cout << "Sorry, that was not a valid entry.
Please try again \n";
menu(); // it redisplays the menu
}// end of switch
cout << "The answer is " << answer << "\n";
cout << " Press the enter/return key to continue
\n";
cin >> somechar ; // it does not matter what they
// press
menu () ; // redisplay the menu.
}// end of menu function
float circle_area(float radius)
{
float area;
area = 3.14 * ( radius * radius);
return area;
}
float triangle_area(float height, float base)
{
float area;
area = .5 * (base * height);
return area;
}

float rectangle_area(float height, float width)
{
float area;
area = height * width;
return area;
}
Step 3: Compile the code.

Step 4: If all goes well, you should see something like what is displayed in Figure 5.2A.


Figure 5.2A: Switch statements.
Hint! You should note that when we include a header file that we create, it is put inside quotation marks, not inside brackets. Header files that are not found in the include directory that installed with your compiler must be put inside quotation marks, and must include the .h extension. The include directory is the directory/folder where the compiler looks for various header files such as iostream, fstream, and cmath.


This is the longest program you have seen yet in this book but don’t be concerned. We are going to review this program, piece by piece, and see what is happening. Hopefully your reading thus far, combined with the numerous comments in the previous code, have given you at least some understanding of what is happening. To begin with, we put the menu in a separate function. The reason for this is so that you could call it repeatedly. You will note that after the answer is returned and displayed on the screen, that we call the menu function again. This means that each time an operation is done, the menu will redisplay and the user can then choose to either perform another operation, or to exit. You should also notice that the function prototyping is all done in a header file.

The actual menu function is the largest and most complex function in this program. The first part of it simply uses a series of cout statements to display choices on the screen, then it prompts the user to make a selection. That selection is stored in a variable named menuchoice. (This name indicates what the variable does.) Then we have a switch case statement that selects a course of action based on the value in that variable. Depending on what choice the user made, the user would be prompted for specific input, the area of the shape they chose would be compu
s42000 4:51 PM - 10 November, 2006
ted, and then the answer would be returned. Because returning the answer will be the same for all the various choices, that is left until after the switch case. Also notice that after the answer is displayed, the menu is redisplayed. This allows the user to make multiple selections.

Watchout! Remember that you must have break statements after each case. Without them, the next case statement will also be executed.


As you can see, the switch statement is more versatile than the if statement. Anytime you have more than two or three choices you should definitely consider using the switch statement rather than an if statement. Also note you have a default option with switch statements that you do not have with if statements.

Example 5.3b
Step 1: Type the following code into your favorite text editor and save it as 5.3b.cpp.

#include <iostream>
using namespace std;
void menu();
int main()
{
menu();
return 0;
}// end of main
void menu()
{
int choice;
float area, base, height, radius;
cout << "1. Area of triangle \n";
cout << "2. Area of circle \n";
cout << "3. Exit \n";
cin >> choice;
switch(choice)
{
case 1:
cout << "1. metric \n";
cout << "2. english \n";
cin >> choice;
cout << "Enter base \n";
cin >> base;
cout << "Enter Height \n";
cin >> height;
area = .5f * (base * height);
switch(choice)
{
case 1:
cout << "The area is "<<area << " square
meters \n";
break;
case 2:
cout << "The area is "<< area <<" square feet
\n";
break;
default:
cout << "Invalid Choice \n";
}// end of inner switch
break;
case 2:
cout << "1. Metric \n";
cout << "2. English \n";
cin >> choice;
cout << "Enter the radius \n";
cin >> radius;
area = 3.14f * (radius * radius);
switch(choice)
{
case 1:
cout << "The area is "<<area << " square
meters \n";
break;
case 2:
cout << "The area is "<< area <<" square feet
\n";
break;
default:
cout << "Invalid Choice \n";
}// end of inner switch

break;
case 3:
return;
break;
default:
cout << "Invalid selection \n";
}
menu();
}
Step 2: Compile and execute this code. You should see something similar to what is shown in Figure 5.2B.


Figure 5.2B: Nested switch statements.
You can see how nested switch statements can be used to provide another layer of possible branching. Nested if statements, switch statements, and loops are very common, you will probably encounter them often.




For Loops
The for loop is perhaps the most commonly encountered loop in all programming. Its structure is the same in all programming languages, only its implementation is different. It is quite useful when you need to repeatedly execute a code segment, a certain number of times. The concept is simple. You tell the loop where to start, when to stop, and how much to increase its counter by each loop. The basic structure of a for loop is shown in Figure 5.2C.


Figure 5.2C: The structure of a for loop.
The essence of the for loop is in the counter variable. It is set to some initial value, it is incremented (or decremented) each time the loop executes. Either before or after each execution of the loop the counter is checked. If it reaches the cut-off value, stop running the loop.

The specific implementation of the for loop in C++ is shown here:

for (int i = 0; i < 5; i++)
{
}

What this code is doing is rather straightforward. First, we create an integer to be used as a loop counter (to count how many times the loop has executed) and we give it an initial value of zero. We then set the conditions under which the loop should execute. That’s the i < 5 portion of the code. It is essentially saying, “keep going as long as i is less than 5.”As soon as that condition is no longer true (i.e., i is equal to 5 or greater than 5), the loop stops executing. Finally, we have a statement to increment the loop counter after each iteration of the loop. Notice the semicolons in the for loop declaration. You should recall that all statements/expressions in C++ end with a semicolon. These code snippets are, indeed, valid statements and could be written as stand-alone expressions. The reason the last one does not have a semicolon is because it is followed by a closing parentheses and that terminates the expression. The three parts to the for loop declaration are the following.

Declare and initialize the loop counter.

Set the conditions under which the loop will execute.

Increment the loop counter.

Example 5.4
Step 1: Use your favorite text editor to enter the following code.

#include <iostream>
using namespace std;
int main()
{
for (int j = 0; j < 10; j++)
{
cout << "Going Up…." << j << "\n";
}// end of for loop
return 0;
}// end of main
Step 2: Compile the code.

Step 3: When you run the code, you will see something similar to what is displayed in Figure 5.3.


Figure 5.3: For Loops.
This simple example will show you how a for loop works. Its rather simple but should give you the basic idea.

It should be pointed out that it is possible to increment by values greater than one, and even to count backwards, using the decrement operator. The next example illustrates this:

Example 5.4a
Step 1:

#include <iostream>
using namespace std;
int main()
{
for (int j = 10; j >0; j—)
{
cout << "count down… << j << "\n";
}// end of for loop
cout << "Blast Off!!! \n";
}// end of main
Step 2: Compile the code.

Step 3: When you run this program you should see something like what is displayed in Figure 5.4A.


Figure 5.4A: For loops 2.
You will find many programming situations where the for loop is quite useful, so it’s rather important. Also remember that for loops, like if statements, are found in all programming languages, only their implementation is different.

Loops, like if statements and switch statements, can be nested. You can have a loop inside of another loop. When you study algorithms in Chapter 13, and games in Chapter 14, you will see places where this is practically applied. The most important thing to remember when nesting loops is that the inner loop will execute a number of times equal to its counter multiplied by the outer loops counter. Put another way, if your outer loop executes 5 times, and you set the inner loop to loop 4 times, the inner loop will actually loop 20 times. It will loop 4 times, for each iteration of the outer loop. Let’s look at an example of this.

Example 5.4b
Step 1: Enter the following code into a text editor and save it as 05-04b.cpp.

#include <iostream>
using namespace std;
int main()
{
for (int i = 0;i<3;i++)
{
for(int j=0;j<4;j++)
{
cout << "This is inner loop " << j ;
cout << " of outer loop " << i << endl;
}// end of inner loop
}// end of outer loop
return 0;
}// end of main
Step 2: Compile and execute the code. You should see something like what is displayed in Figure 5.4B.


Figure 5.4B: Nested for loops.
Note how often the inner loop printed out. This should prove to you the earlier statement regarding the number of iterations an outer loop makes. The outer loop, in this case, was set to loop 3 times. The inner loop was set to loop 4 times. Because the inner loop was nested within the outer loop, it actually looped 3 multiplied by 4, or 12 times.

Do Loops
The for loop is the most common type of loop; however, it is not the only type of loop. There are other loop structures you can use, although they all accomplish the basic goal of executing a given piece of code a specified number of times. The do loop is one such loop structure. Unlike the for loop, however, it does not evaluate whether or not the loop should continue until after the loop has completed an iteration. The following is the generic structure.

Do
{
// place code here
} while (some condition is true)
The following is a more specific example.

Example 5.5
Step 1:

#include <iostream>
using namespace std;
int main()
{
int x;
do
{
cout<< x ;
x++;
}while (x < 10);
return 0;
}
You can see that the do loop does essentially the same thing as the for loop. However, the loop condition is not evaluated until after the loop has executed an iteration, and the loop counter is incremented inside the loop. These loop structures give you different options for accomplishing the same basic goal.







While Loops
While loops are almost identical to do loops. They are simply structured a little bit differently. The do loop has the condition to be evaluated at the end of the loop, whereas the while loop has it at the beginning.

while(condition)
{
}
The following is an example of a while loop.

Example 5.6
Step 1: Type the following code into your favorite text editor.

#include <iostream>
using namespace std;
int main()
{
int i = 0;
while(i < 10)
{
cout << "I is " << i << "\n";
i++;
}
return 0;
}// end of main
Step 2: Compile the code.

Step 3: Run the code. You should see something like the image in Figure 5.5.


Figure 5.5: While loops.
As you can see, all loop structures accomplish essentially the same goal. They execute a given block of code a certain number of times. The only differences are where you check the value of the loop to see if you will continue looping, and where you increment the loop counter. C++ loops are best described by the old axiom ”There is more than one way to skin a cat.”

Chapter 6: File Input and Output
Download CD Content
Chapter 2 introduced you to screen input and output. Chapters 3, 4, and 5 made use of this practical information. In this chapter, you will learn how to get input from a flat file and send output to a flat file. This can be very useful. There are times when you will need to import data from a comma delimited text file, or perhaps you wish to write errors to a log file. All this, and more, can be accomplished with file input and output.

Importing data from a flat file is, in essence, quite similar to getting data in from the keyboard. And outputting to a file is similar to outputting data to a screen. C++ handles both in similar ways, so if you fully understood the input and output techniques in Chapter 2, then this chapter should not pose any great challenges for you.

What Is a Flat File?
A flat file is simply a file that has no structure. Thus, its name—it is flat, in that it has no structure or relationships. Data is simply put into the file with no interrelationships between entries in a file, or between files. Database files (such as Microsoft Access files or .mdb files) have a definite structure. Database files also have clearly defined relationships between entries (called records) and even between different files. However, long before there were relational databases, there where flat files. You might think that with the advent of relational databases flat files are now irrelevant. However, this is not true. There are many cases where it is more appropriate to store data in a flat file than in a complex relational database. One such situation is when writing a log of events or errors.

When you open notepad and create a text file, you are creating a flat file. Any file that simply contains ASCII (The American Standard Code for Information Interchange), pronounced AZ KEY, text is a flat file. In addition to ASCII code there is now Unicode. Unicode is simply an expanded version of ASCII, made to handle international symbols. In fact, the first 255 characters of the Unicode set are the ASCII codes. An in-depth discussion of ASCII and Unicode is beyond the scope of this book. Just remember that text files are flat files. And remember what the ASCII character codes are. Figures 6.1A and 6.1B show the entire ASCII code set. You can also find references to the ASCII code set on the Internet (search ASCII character code) and in the help files that ship with many commercial software development tools.


Figure 6.1a: The first 126 characters of the ASCII code set.

Figure 6.1b: The last half of the ASCII code set.


ifstream and Flat Files
The ifstream object is used to input from files. For now, you should think of an object or a class as a group of related functions all grouped together into a single bundle. That bundle is what we are calling a class or an object. We will be exploring in greater detail exactly what classes and objects are later in this book. In fact, three chapters are devoted to this topic.

The word stream in the name should be of interest to you. Files are input and output in C++ in the form of a stream. A stream is simply a running thread in memory. It is literally a stream of bytes, with each byte representing a character in the file. In the C++ programming language, all input and output occurs in streams of bytes. A stream is simply a sequence of bytes. Input streams receive bytes from some device—usually the keyboard or, in the case of ifstream, a file on the disk.

Basically, the ifstream class is a group of functions used to input files. The ofstream class is used to output to files. The functionality of both are combined in fstream. These objects can be used in your code to represent specific files, and to manipulate those files. You can input and output to a file using ifstream, ofstream, and fstream. Each of these objects will treat the file as a stream of bytes, with each byte representing a single character in the file. Thus, this is the reason for the word stream in the names of these objects. It is the same as with cout and cin from the iostream header file. They treat the keyboard input and the screen output as a stream of bytes. The only real difference is that cout sends data to the screen and ofstream sends it to a flat file. They both handle the data in much the same manner.

Output streams send their sequence of bytes to some device—usually the monitor—but in the case of ofstream the bytes are sent to some file on the hard disk. As was mentioned earlier, the underlying function is the same as output you saw in Chapter 2, it is only the destination that is really different.

You can create an instance of this class just like you would any other variable with one exception. After the name you give your variable you will have open and close parentheses. In some cases, these parentheses will have parameters in them; in others they will not. The following is the most common, and the simplest, way to create an instance of this ifstream.

ifstream fin();

With this line of code, we have just created a variable called fin. That variable is of the type ifstream. That means that it is an object that represents a file to be input. This object, ifstream, has a number of methods and properties that you will be able to use in your programs. Table 6.1 summarizes the most commonly used of these.

Table 6.1: ifstream Methods and Properties Method/Property
Purpose

clear
This method simply clears the contents of the buffer.

close
Closes the file you previously opened.

eof
This property is a Boolean and tells you if you are at the end of the file you have opened.

get
This method gets a single character.

getline
This method gets an entire line.

is_open
This is a Boolean property that is true if the file is open and false if it is closed.

open
Opens a file and attaches it to the filebuf object and, thus, to the stream.

setmode
Sets the stream’s mode to binary or text.

read
This method simply reads in data from the stream. The data will be in binary mode.

seekg
When a file is opened in binary mode you can tell it to go to a particular space in the file. This method does that.

tellg
This method retrieves the current position of the pointer in the file.


You can see that a lot of these methods mention a stream. You might be wondering what this is referring to. The most important thing for you to remember is that C++ handles file input and output as streams of characters. Actually, it handles screen/keyboard input and output the same way, but with cout and cin it’s not as obvious. A stream is simply a flow of individual characters, flowing much like a stream of water, thus the name.

The properties are designed simply to let you know the current state of the file. (Is it open or not?) The various methods you see in Table 6.1 are primarily concerned with opening the file, reading it in (either one character at a time, or one line at a time), and closing the file. The exception is the setmode method. It determines how the file will be opened. By default it is opened as text. You do, however, have some options as to how you open it. You can set the mode to text or binary. You will probably use the text mode most of the time.

Example 6.1
This example will illustrate how to read-in text data from a text file. The data is simply read in to a variable then displayed on the screen.

Step 1: Enter the following code into your favorite text editor.

#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
char buffer[256];
ifstream myfile ("test.txt");
while (! myfile.eof() )
{
myfile.getline (buffer,100);
cout << buffer << endl;
}
return 0;
}
Step 2: Compile the code.

Step 3: Run the code. You should see something like what is shown in Figure 6.1C.


Figure 6.1C: File input.
Let’s consider this code for a few moments to make sure you understand what is happening. First, we have the include statements that you see at the beginning of all C++ programs. The fstream file is where we get the file input stream that allows us to read in a file. Next, inside the main function, we declare a character array named buffer. This is literally a buffer that is used to store the data as it’s read in.

The next line of code that is of interest to us is the while (!myfile.eof()). This is a basic while loop that is using the negation operator (!) on the end of file property of the myfile object. What this code is essentially saying is that “while it’s not true that this is the end of the file, keep looping.” As soon as the end of file is reached, the loop will stop executing. Finally, we see the getline method used to retrieve an entire line of text from the keyboard input. Remember that the getline function allows you to determine how many bytes will be read in, thus preventing you from over flowing an array.

Watchout! Notice that the file we chose to open in this example has no path, it is in the same directory as the program. If your file is in a different directory, you must use a full path. However, remember that inside strings the \ character denotes an escape key, so to put that character in you have to use a double slash \\. The following is an example. ifstream myfile ("c:\\myfolder\\test.txt");




ofstream and Output
You now have a basic understanding of text file input. What about output? You may wish to write things to a file from time to time. It’s very similar to inputting a text file. Inputting a file requires the ifstream object. Outputting uses the ofstream object. The methods of ofstream are quite similar to the methods of ifstream with a few exceptions. The major methods are shown in Table 6.2.

Table 6.2: ofstream Methods and Properties Method
Purpose

open
This works just like the open method in ifstream; it opens a file.

close
This method closes a previously opened file.

attach
This attaches your current stream to an existing file. It is useful if you wish to append the contents of your stream to another file.

is_open
This property returns true if the file is open.

seekp
This method sets the pointer location in the file.

tellp
This method retrieves the current pointer in the file.

write
This method writes a sequence of characters to a file.


This next example opens a file, then writes text to it. All of this is done using the ofstream.

Example 6.2
Step 1: Open your favorite text editor and enter the following code.

#include <fstream>
int main ()
{
ofstream myfile ("test2.txt");
if (myfile.is_open())
{
myfile << "This outputting a line.\n";
myfile << "Guess what, this is another line.\n";
myfile.close();
}
return 0;
}
Step 2: Compile the code.

You can see that this code is quite similar to the file input code. Note that the << operator is used here, just as it was with cout. C++ tries to make input and output very similar whether it’s screen/keyboard or files. These previous two examples demonstrate the basics of input and output of text files. You will use these techniques again later in this book.


Sequential Files
A sequential file is simply a file where the data is stored one item after another. The flat text files you have dealt with so far are sequential files. A more technical definition would be that a sequential file is a collection of data stored on a disk in a sequential, nonindexed, manner. C++ treats all such files simply as a sequence of bytes. Each file ends with a special end of file marker. Sequential files do not have additional inherent structure. Any additional structure must be imposed by the program reading and writing the file. What this means in plain English is that there is no way to move around in a file. You just start at the beginning and input the entire file from start to finish. You can open these files in a variety of ways. Of course, you will still have to include ifstream and/or ofstream.

Example 6.3
Step 1: Declare a variable of type ifstream/ofstream, depending on whether you need input or output. This variable is often referred to as a file handle.

ifstream infile; // declares file handle called
// infile
ofstream outfile; // declares file handle called
// outfile
fstream inoutfile; // declares a file handle that
// can be either
Step 2: Open the file for reading, using the ifstream member function open(). When you open it you pass it the name/location of the file you wish to open, and the mode you wish to open it in. The mode tells it whether this is input, output, or both.

infile.open("myfile.txt", ios::in); //for reading only
outfile.open("myfile.txt", ios::out); //for writing only
inoutfile.open("myfile",ios::in|ios::out); //for reading
//& writing
outfile.open("myfile.txt", ios::app); //for appending
outfile.open("myfile.txt", ios::trunc);

This last one is rather interesting. The truncate option says that “if the file already exists, then wipe it out and start with a new file.” You should, obviously, be quite careful with this one.

When you need to go to file that is not in the same directory/folder as your program, you will need to specify the path.

Watchout! Remember that the \ in C++ denotes an escape character. So you must use \\ to denote directories. The following is an example of the wrong way and the right way to do this. WRONG: infile.open("c:\myfolder\myfile.txt", ios::in); CORRECT: infile.open("c:\\myfolder\\myfile.txt", ios::in);


Let’s look at an example that combines all the major modes for opening a file. This will let you see how each of them work.

Example 6.4
Step 1: Enter the following code into your favorite text editor.

#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char buffer[256];
// open it for output then write to it
fstream myfile;
myfile.open("test2.txt",ios::out | ios::trunc);
if (myfile.is_open())
{
myfile << "This outputting a line.\n";
myfile.close();
}
// open it for input and read in
myfile.open("test.txt",ios::in);
myfile.getline(buffer,100);
cout << "The file contains " << buffer << "\n";
myfile.close();
//open for appending and append
myfile.open("test.txt",ios::app);
myfile << " Hey this is another line \n";
myfile.close();
// open for input and print to screen
// open it for input and read in
myfile.open("test.txt",ios::in);
myfile.getline(buffer,200);
cout << "The file contains " << buffer << "\n";
myfile.close();
return 0;
}// end of main
Step 2: Compile the code.

Step 3: Run the code.

In this single example, you can see a file object being opened several times in several different modes. This should illustrate to you the various uses of the modes for opening a sequential file.


Binary Files
Text files are not the only type of flat files you can use. You can also use binary files. Binary files are still flat files; however, they are in basic binary format rather than ASCII. Remember that everything in a computer is binary (1’s and 0’s). The binary format has each file stored in a byte-by-byte format. This produces some odd-looking results if you try to view binary files like plain text. For example, an integer might be represented by four separate characters, because it occupies four bytes. You might ask why anyone would want to open a binary file. There are a number of reasons, the most prominent being that there is still old data stored this way. However, one useful thing you can do is to open any file in binary mode and count the bytes in it, to see how big the file is. This next example demonstrates this.

Example 6.5
Step 1: Enter the following code in your favorite text editor.

#include <iostream>
using namespace std;
#include <fstream>
int main ()
{
long start,end;
// Recall from chapter one, that a long is simply
// large integers
ifstream myfile ("test.txt", ios::in|ios::binary);
start = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size of " << "test.txt";
cout << " is " << (end-start) << " bytes.\n";
return 0;
}
Step 2: Compile this code.

Step 3: Run the executable. You should see something like Figure 6.2.


Figure 6.2: Binary file size.
This code is relatively straightforward, let’s take a look. To begin with, we open a file just as we would normally do, except we open it as binary, with the following line of code.

ifstream myfile ("test.txt", ios::in|ios::binary);
Next, we retrieve the beginning point for the file.

start = myfile.tellg();

And then we get the endpoint of the file, by first moving to the end of the file then getting the position.

myfile.seekg (0, ios::end);
end = myfile.tellg();
The first line says to start at the 0 byte/character and search until the end of the file. If you wanted to start at another point such as the 10th character or byte, you could simply put in a 10 where the 0 is. Now it’s just a matter of subtracting the beginning point from the endpoint and that’s how many bytes of data the file has in it. The process is not particularly complicated. However, you might be wondering about the ios you keep seeing. That is simply C++’s way of saying “input/output stream.”

Chapter 7: Exception Handling
Download CD Content
In any programming situation various problems can occur. You can have basic errors of many types. Handling those problems is of paramount importance. You do not want your program to crash when an error occurs. If this were to occur, the people using your software (programmers generally refer to them as “users”) would be very unsatisfied with your product. A better idea is to correct the problem or at least give the user a friendly message telling them what has occurred. Exception handling is, therefore, a critical topic in programming.

Different programmers have different philosophies regarding exception handling. However, it is commonly believed that you cannot have too much exception handling. Code should be contained inside some exception handling.

Errors and Exceptions
There is an almost limitless list of things that can go wrong. Think back to Chapter 5: What would happen if you tried to open a file that wasn’t there? You would get an error, and without error handling your program would crash. What if you asked a user to enter a number and they typed in their name, then your code tried to store their input in an integer variable? You would get an error, and, yes, without error handling your program would crash.

Errors can be grouped into three main categories, each of which is described in Table 7.1.

Table 7.1: Categories of Errors Error Type
Description

Syntax
A syntax error occurs when you have attempted to use the language in a way that is inappropriate. For example if you said “if (x $ $ y)” when you meant to write “if (x==y)” that would be a syntax error. The compiler will not compile your code if you have any syntax errors.

Runtime
This is an error that occurs when you run your program. It is any interruption to the normal flow of your application. Trying to open a file that does not exist and dividing by 0 are two examples of runtime errors. These errors are also called exceptions.

Logic
This occurs when your program compiles and runs properly, but produces erroneous results. There is some error in your programming logic. This can be the hardest type of error to find and is what is generally referred to as a “bug.”


Now for the really bad news—you will have errors. It’s a fact of life that when you write programs you get errors. The first thing you can do is thoroughly test your programs to attempt to uncover and fix errors before distributing the program. The other thing you can do is provide adequate error handling so that errors don’t cause your program to crash. Error handling will take care of runtime errors and the compiler will identify syntax errors. Logic errors are what will be your biggest problem. At the end of this chapter, we will explore some techniques to help you in debugging applications.



try-catch Blocks
C++ offers a rather powerful error-handling tool called the try-catch block. This technique is also used in Java and VB.net™, so this is a skill you will be able to carry over to other programming languages. The try-catch block consists of two sections. The first is the code that you want to execute. This is the code that you try. If an exception is generated then the catch block catches it. Thus, the catch block is where your error handling goes. The following example illustrates this point.

Example 7.1
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
using namespace std;
#include <fstream>
int main ()
{
try
{
char buffer[256];
ifstream myfile ("test.txt");

while (! myfile.eof() )
{
myfile.getline (buffer,100);
cout << buffer << endl;
}
}// end of try block
catch(…)
{
cout << "There was an error !\n";
}
return 0;
}

Step 2: Compile the code.

Step 3: Run the code.

Now, if the file is found, then things will work out as they always have. But if for some reason the file is not found, then the runtime error will be caught and the user will get a simple error message. To test this you can simply change the file name to one that does not exist on your PC.

You probably also noticed that the catch block has three dots in the parentheses. This means that all exceptions should be handled by this single catch block. You will see later in this chapter that you can handle different types of exceptions differently.

Essentially, what you see in the previous example is that the code in the try block is attempted. If it executes without error, then the catch block will never be executed. If an error occurs in the try block then execution of that code stops and the catch block is executed. There should be absolutely no code whatsoever between the closing bracket of the try block and the opening bracket of the catch block.

Watchout! If you do not use try-catch blocks, then any exception that occurs will cause your program to cease working.


It is also rather common practice for C++ programmers to set up a series of try- catch blocks, each catching a different type of error. What happens is, depending on what is wrong, your code will “throw” a different type of message, such as an int, string, and so on. You then have a series of catch blocks that catch each of these types of errors. Consider the following example.

Example 7.2
Step 1: Enter the following code into your favorite text editor.

#include <iostream>
using namespace std;
int main()
{
int answer, divisor, dividend;
try
{
cout << "Please enter an integer \n";
cin >>divisor;
cout << "Please enter another integer \n";
cin >> dividend;
if(dividend ==0)
throw 0;

answer = divisor/dividend;
cout << answer;
return 0;
}
catch (int i)
{
cout << "You cannot divide by zero";
}
}
Step 2: Compile the code.

Step 3: Run the code. Enter 0 for the second number. You should see something like what is depicted in Figure 7.1


Figure 7.1: Multiple catch blocks.
You can see that this catch block only catches integers. If the dividend is 0, then we throw an integer. It would be a simple matter to throw a variety of exceptions using different data types for each error type.


Exception Classes
Up to this point in the chapter, we have handled all the exceptions the same way. This is quick and easy, but not always the best method. Think about it this way—different errors will require different handling. If the error is a “file not found,” then you probably want to prompt the user to enter a different file name. If the error is a division by 0 error, then you probably want to prompt the user to enter a non-0 number. Some functions of the standard C++ language library send exceptions that can be captured if we include them within a try block. These exceptions are sent with a class derived from std::exception as type. Each exception has a specific class associated with it. This class (std::exception) is defined in the C++ standard header file <exception> and serves as pattern for the standard hierarchy of exceptions. Again for now you should simply think of a class as a bag of functions. (Classes will be discussed soon!) Figure 7.2 summarizes some of the more commonly encountered exception classes.


Figure 7.2: Exception classes.
Hint! Microsoft defines its own set of exception classes for use with Visual C++, however, the standard exception classes will work with Visual C++ and with all other C++ compilers.


The hierarchy you see demonstrated in Figure 7.2 is not exhaustive. It does, however, show you the relationship between exceptions. This becomes important when you are handling multiple exceptions. You can trap specific errors and handle them differently. You must remember that you have to trap exceptions in the reverse order of how they appear on the hierarchy. What this means is that if you trap run_time_error you cannot then have another catch statement for FileAccessError after that. The reason is that the exception higher up in the hierarchy includes all lower exceptions that come under it in the hierarchy. Put another way, you should trap the most specific and, therefore, lower-level exceptions first, then work your way toward more general exceptions.

Once we move forward into classes and object-oriented programming, you will learn how to create your own exception objects.




Throwing Exceptions
In addition to catching exceptions, you can simply throw them. Throwing an exception simply sends the exception back to the function that called the current function, so that the previous function can handle the exception. The following example illustrates this.

Example 7.3
Step 1: Enter the following code in your favorite text editor.

#include <iostream>
using namespace std;
// function prototypes.
float divide_number(float , float);
int main()
{
float dividend,divisor,answer;
try
{
cout << "Please enter a number \n";
cin >> dividend;
cout << "Please enter a number \n";
cin >> divisor;
answer = divide_number(dividend,divisor);
cout << dividend << " divided by ";
cout << divisor << " is " << answer;
}// end of try
catch(...)
{
cout << "oops, there is an error!";
}// end of catch
return 0;
}
float divide_number(float num1, float num2)
{
try
{
float answer;
answer = num1/num2;
return answer;
}
catch(...)
{
throw;
}//end of catch
Step 2: Compile the code.

You can see that exceptions are not handled in the various functions, only in the main function. Some programmers prefer to centralize their error handling in this way.



Saving Errors to Logs
Sometimes it is simply not helpful to display error messages to the user. If the error is not critical, it’s more likely to simply confuse your end user without accomplishing anything useful. In fact, it is not prudent to display all messages to the user. One answer to this is to simply log the error messages to a flat file. Later, support personnel can read the log and see what has been occurring and perhaps diagnose what is wrong. You can even combine a message to the user with a log entry if you wish. The following example shows you how to log error messages to a file.

Example 7.4
Step 1: Enter the following code into your favorite text editor.

#include <fstream>
#include <iostream>
using namespace std;
void logerror(int);
int main()
{
int answer, divisor, dividend;
try
{
cout << "Please enter an integer \n";
cin >>divisor;
cout << "Please enter another integer \n";
cin >> dividend;
if(dividend ==0)
throw 0;

answer = divisor/dividend;
cout << answer;
return 0;
}
catch (int i)
{
cout << "You cannot divide by zero";
logerror(0);
}
catch (...)
{
logerror(1);
}
}
void logerror(int type)
{
fstream myfile;
myfile.open("error.txt",ios::app);
if (type==0)
myfile<<"Division by zero error \n";
else
myfile<< "INdeterminate error \n";
return;
}

Step 2: Compile the code.

Step 3: Run the code. You should see something like what is depicted in Figure 7.3.


Figure 7.3: Writing errors to a log.
Now, if you open the file called error.txt on your hard drive, you should see something similar to Figure 7.4.


Figure 7.4: Viewing an error log.
This code sample has illustrated a number of important things. The first, and most obvious, is that you can log errors to a flat file if you so desire. But what you have also seen in this example is a variety of techniques from the past several chapters brought together. If you view each chapter and lesson as a separate and discrete entity, then you will miss the real point of this book. You should work to combine different techniques so that they work together to create useful applications.

General Testing and Debugging
As this chapter has already pointed out, you will want to use extensive error handling to take care of any errors that occur during the execution of your code. However, an even better idea would be to properly test your code before you send it out. Good testing is a vital skill, and one that is rarely discussed in introductory C++ books.

There are three types of data you should test, and there are three types of testing you should do. The three types of data are: valid data, invalid data, and extreme data. The first, valid data, is simple. Type in the sort of data that your program is expecting and see whether it works. That is something most programmers, even beginners, address. The second area, invalid data, is sometimes overlooked. What happens if your program asks for an integer yet the user types in “A”? And, finally, you should check what happens with extreme data. If you ask the user to enter their age, and they enter 300 instead of 30, does your program just blindly go along with that clearly fallacious input? Or is your program smart enough to warn the user that their input is simply not possible? The discussion of data validation, later in this chapter, will show you how to accomplish this. For now, remember, when testing your program, to make certain that you test with all three types of data.

Now that you know what type of data to test, we can discuss how to test. There are three types of testing: unit testing, stress testing, and beta testing. Unit testing literally means to test the software on a single unit, normally your own PC. You would test all three types of data, but you would simply test them on your own machine. Stress testing involves pushing the program to its limits. If it is a multiuser program, then put a large number of users on it simultaneously. If its designed to handle 50 calculations per hour, then push it to at least 50 (actually going 10% beyond 50 would be even better). And, finally, we have beta testing. This involves simply getting your program to a handful of users and getting their feedback.

A lot of software today is inadequately tested. The news is filled with reports of software flaws, some causing significant problems. It is absolutely vital that you thoroughly test your software.

As you test your software you may find flaws. These are usually referred to in the industry as “bugs.” It is amazing how many programmers are not very skilled at locating such bugs. Most programmers can easily fix a problem once it is found, but have difficulty finding it. There are some simple techniques you can use to find bugs in your programs.

One technique is to selectively comment your code. If the compiler tells you that there is an error, then simply comment out half your code and see if you still get the error. If you do still receive the error, add one half of the remaining code to your commented section and try to compile again. If you do not still receive the error, remove the comments from the one half you already commented. The following code has an error and generates a compiler error message syntax error : missing ; before identifier cout. Obviously, there is a problem with a missing semicolon before a cout statement, but which one? You could reread them all, and in a small program, that’s probably the best thing to do. In a large program, however, doing this will not work. Let’s take the section that has cout statements (the main function) and comment out half of it and see what happens.

// Include statements
#include <iostream>
using namespace std;
float cube_number(float num);
float square_number(float num);
int main()
{
float number;
float number3;
cout << "Please enter a number \n";
cin >> number;
if (number > 0 && number < 100)
{
number3 = cube_number(number);
cout << number << "cubed is "<< number3;
}// end of if
else
{
number3 = square_number(number)
cout << number << "square is "<< number3;
}// end of else

if (number3 <10000 || number3 ==2)
{
number3 = square_number(number3);
cout << number3 << "squared is "<< number3;
}// end of second if
return 0;
}// end of main
float square_number(float num)
{
float answer;
answer = num * num;
return answer;
}
float cube_number(float num)
{
float answer;
answer = num * num * num;
return answer;
}
To find that error, comment out half the code and then try to compile again.

int main()
{
float number;
float number3;
cout << "Please enter a number \n";
cin >> number;

if (number > 0 && number < 100)
{
number3 = cube_number(number);
cout << number << "cubed is "<< number3;
}// end of if
/* BEGIN COMMENTING OUT CODE FOR TESTING
else
{
number3 = square_number(number)
cout << number << "square is "<< number3;
}// end of else
if (number3 <10000 || number3 ==2)
{
number3 = square_number(number3);
cout << number3 << "squared is "<< number3;
}// end of second if
END COMMENTING OUT CODE FOR TESTING */
return 1;
}// end of main
After compiling the code again, no errors are found. The problem, therefore, is in the section that was commented out. This technique can help you to drastically shrink the area you have to examine for a flaw. When writing larger programs, this will be helpful.

It is also important to look at the area surrounding an error. If you use one of the commercial IDEs such as Microsoft Visual or Borland C++ Builder, then the IDE can let you go directly to where the error is generated. However, sometimes the error is actually caused by code prior to where the error shows up. For example, a missing semicolon at the end of one line will cause the compiler to try to execute the next line as if it were part of that line. Thus, a good rule of thumb is to check the preceding four or five lines of code. Also remember the most common errors are the following.

Spelling

Missing semicolons

Forgetting to close a bracket around a block of code

Forgetting that C++ is case-sensitive

Always look for these errors. In fact, whenever you finish writing a significant section of code, it’s a good idea to give it a quick read-through to search for these types of errors.

Another commonly used technique is to use cout statements at various locations in your code to print-out the value of certain variables. If you have a calculation that is not performing correctly, then this may be your best debugging technique. If you can see the values of the pertinent variables at each stage in the process you will be able to identify precisely where the problem occurs.

These are just a few “tricks of the trade” that might help you in debugging your applications. The important thing to remember about these techniques, and others, is that they are for debugging, not producing code. When you are finished debugging and testing, make sure you uncomment any code blocks that you commented out, and remove any cout statements that you put in for debugging purposes.

Chapter 8: User-Defined Data Types
Download CD Content
Overview
Throughout this book you have been using a variety of different variables of different types (int, float, bool, etc.). However, all these data types have something in common; they each store a single value. That statement may seem so obvious as to not need stating. However, having a variable store only a single value is not the only option you have when programming with C++. Another option is to create user-defined data types. User-defined data types are data types that you create. They allow you to store several, hopefully related, values under a single variable name. You literally create your own new data type. The difference between your data types and the ones that are part of the C++ language is that yours are complex and hold more than one value.

A structure is one of the most common sorts of user-defined data type. That means that you, the programmer, essentially create your own new data type to suit your needs. Structures are just one category of user-defined data types, but they are perhaps the most commonly used. Other user-defined types include typedefs, unions, and enumerations. Each of these user-defined data types will be explored and demonstrated in this chapter. The different categories of user-defined types are summarized in Table 8.1. Each will be explained in detail later in the chapter.

Table 8.1: User-Defined Types User-Defined Type
Purpose
Example

Structure
A compound data type that simply combines several related pieces of data.
Struct employee
{
char lastname[30];
float salary;
};

Typedef
Provides a different name, or an alias for an existing data type.
Typedef int RETURN;
Typedef double ANSWER;

Union
A combination of different data types.
Union NumericType
{
int
iValue;
long
lValue;
double dValue;
}

Enumeration
An enumeration is a user- defined type that defines named constants.
enum
test{value1,value2,value3};

Bit Field
A type of structure that allows you access to individual bits.
Struct status
{
unsigned :cleartosend;
unsigned :ringing;
}
DJ_QB 5:29 PM - 10 November, 2006
banned
DJ_Mike_Coquilla 5:37 PM - 10 November, 2006
S42000,

on your second post, 343 lines down... for some reason, it doesn't correlate to what you posted on your 4th post (see 655th line starting from the center). can you please elaborate?
s42000 5:55 PM - 10 November, 2006
oops that was a typo ... but the 763rd line makes it all clear. It reads ...

Quote:
That means that you, the programmer, essentially create your own new data type to suit your needs


But in all reality, with all things being equal, however that is not usually the case, the subtle nature of things, some inanimate, tend to gravitate towards a destiny that sometimes but not all times may be predetermined but there is no universal understanding of such predicaments.
djzoo 6:24 PM - 10 November, 2006
Quote:
leave it to nik39 top flight security to have nothing better to do. good job nik maybe you will get that promotion to super cop and get that walkie talkie u've been waiting for.


duh duh duh duuuuhhhhh!
grrillatactics 6:48 PM - 10 November, 2006
Quote:
banned


co-signed.

;-P
kicko 7:25 PM - 10 November, 2006
i must be retarded but i can't see but i can't see aything that says "come on down and share files"
Dj KaGeN 7:26 PM - 10 November, 2006
whatever.. there has been so much crap - worthless fill.
Atleast this has techinical merit.
sixxx 7:40 PM - 10 November, 2006
I like ice cream, sometimes.
grrillatactics 8:18 PM - 10 November, 2006
Quote:
I like ice cream, sometimes.


I love ice cream. Except for breakfast. Although I can't say that I have never had ice cream as a breakfast.
AKIEM 8:31 PM - 10 November, 2006
hope someone reads this:
how about some protocols, guidelines, structure, advice, and support for officially sanctioned local Rane/Serato DJ clinics?
DJ_Mike_Coquilla 9:12 PM - 10 November, 2006
i like to eat glue
Julls 9:14 PM - 10 November, 2006
Quote:
i like to eat glue


Which kind? Elmers?
nik39 9:28 PM - 10 November, 2006
Quote:
I would have to say its partly rane/serato fault for not informing tony about what can & cant be done

Do you really need to say that illegal stuff cant be done? Filesharing is not legal.

Quote:
Quote:
I'll ask again, and please show and prove...

Quote:
What I meant was, that you were using the same "file sharing" comment for previous SSL sessions, I've checked the flyers, and they had the same comment. I didnt know you were using generic flyers for at least the last 2 events.


Please... where are the previous fliers that contained "file sharing?"

You used this for session 4 (the latest), and at least session 2. I have *two* files on my harddisk, both have EXACTLY the same "file sharing" comment. The first one has the filename "RaneSSLFlyerFinal.jpg" (which was linked with the current event), and the second one has the filename "SSL Zen Flyer 2.jpg" (which was linked with session no. 2).
Kool DJ Sheak One 9:33 PM - 10 November, 2006
He said, She said, I heard it through the grapevine.
Nik, just let it rest. Wipe youre hands of this. Pick your battles. You are putting your foot in your mouth now.
Enough already! Sheesh.
m0rph! 9:35 PM - 10 November, 2006
Quote:
s42000 wrote: Filibuster! let it rest ladies ...

LMAO!! That was some classic ish! Thanks for the C++ refresher! ;-)
sixxx 9:38 PM - 10 November, 2006
Quote:
Quote:
i like to eat glue


Which kind? Elmers?


Elmer Fudd. I always thought he was a funny character. Too bad he didint get rich making glue. 'Wabbit!'
nik39 9:38 PM - 10 November, 2006
Kool DJ Sheak One, I answered tonys question before. Nevertheless he asked again and insisted on an answer, THATS why I posted an answer. Dont freaking blame me for answering his questions, jesus. If he doesnt want me to answer tell HIM not to ask.
Detroitbootybass 9:44 PM - 10 November, 2006
Quote:
He said, She said, I heard it through the grapevine.
Nik, just let it rest. Wipe youre hands of this. Pick your battles. You are putting your foot in your mouth now.
Enough already! Sheesh.


Nik does choose his battles very carefully and he is totally correct in this case (as he almost always is)... you, Kool DJ Sheak One, are the only one putting their foot in their mouth.
society 9:49 PM - 10 November, 2006
Quote:
Serato sessions are a great idea... I'm going to see if I can start a bi-monthly session here in Toronto.


Well, I'm a little scared to say this at this point, but mex, if you get this going, let me know--I would be all about it.

Also, that C++ shit was pretty funny.
Dj K.Smith 9:58 PM - 10 November, 2006
Quote:
DJ Michael Basic, nik39's activities in this forum are extremely helpful to us here at Serato. If he were to stop helping because people gave him a hard time, that would be a loss to us.


Yeah Sam, but it's the way dude comes off that gets him the negative feedback... When I first came onto the board, I asked a question and got "Super Sarcasm" from your boy... It was an answer as if I knew all about this forum and how to find out information... The way he tells everyone to PM people, he needs to follow his own advice from time to time...

I can only speak for the first meeting that I attended and can say that we never even discussed file sharing... We we're all so happy just to be able to rock out and jam with each other...

Mike Basic did let everyone use his 57 and that did lead to me solidifying my thoughts to get my own 57... I meet some cool dj's that night and would hate for someone way across the world to fuck up what we're doing here in Cali...
Kool DJ Sheak One 10:01 PM - 10 November, 2006
Quote:
Quote:
DJ Michael Basic, nik39's activities in this forum are extremely helpful to us here at Serato. If he were to stop helping because people gave him a hard time, that would be a loss to us.


Yeah Sam, but it's the way dude comes off that gets him the negative feedback... When I first came onto the board, I asked a question and got "Super Sarcasm" from your boy... It was an answer as if I knew all about this forum and how to find out information... The way he tells everyone to PM people, he needs to follow his own advice from time to time...

I can only speak for the first meeting that I attended and can say that we never even discussed file sharing... We we're all so happy just to be able to rock out and jam with each other...

Mike Basic did let everyone use his 57 and that did lead to me solidifying my thoughts to get my own 57... I meet some cool dj's that night and would hate for someone way across the world to fuck up what we're doing here in Cali...

word
djtonypsalms 10:09 PM - 10 November, 2006
I asked you to "show" & "prove" and all you're doing is just talking... still.

Please upload those previous fliers so everyone can see.

I screwed up, yes, and I've admitted it.

You are claiming that I did this repeatedly, and to me, your judging my character. You're making me look shady.

So, I ask again, and prove it. Show some evidence where I've mentioned file sharing before Session 4.
ejayian 10:09 PM - 10 November, 2006
Quote:
Quote:
I would have to say its partly rane/serato fault for not informing tony about what can & cant be done

Do you really need to say that illegal stuff cant be done? Filesharing is not legal.


Doesnt matter what is printed, its "officialy sponsored" they should have protocols in place to make sure that kind of shit doesnt tarnish there reputation, they cant just asume that nobody makes mistakes. The reason rane/serato got all bent out of shape was because it was "officially sponsored" Im not sure exactly what officially sponsored means but it sounds like everything produced is brought to you by them.

Look at how technical they are when it came time to designing the shirts
Quote:
Serato and Rane do not like seeing their logos "warped or slanty or multi-colored or plaid or paisley". We're serious about this, have a read of this page if you'd like to know more
djtonypsalms 10:09 PM - 10 November, 2006
Nik39,

I asked you to "show" & "prove" and all you're doing is just talking... still.

Please upload those previous fliers so everyone can see.

I screwed up, yes, and I've admitted it.

You are claiming that I did this repeatedly, and to me, your judging my character. You're making me look shady.

So, I ask again, and prove it. Show some evidence where I've mentioned file sharing before Session 4.
sixxx 10:10 PM - 10 November, 2006
Dirt is a good source of iron.
djtonypsalms 10:10 PM - 10 November, 2006
BTW --- These flyers were NEVER printed!!!
iki 10:28 PM - 10 November, 2006
I just bought Serato Scratch Live today. Can't get it to work. Awesome!

ps. What does PM mean..?
Dj KaGeN 10:47 PM - 10 November, 2006
Private Message
m0rph! 11:03 PM - 10 November, 2006
Wow... the thread that just does not want to die! I think I should pull a s42000... FILIBUSTER!

Is a Burrito a Sandwich? Judge Says No
-
Friday, November 10, 2006

(11-10) 13:17 PST Worcester, Mass. (AP) --

Is a burrito a sandwich? The Panera Bread Co. bakery-and-cafe chain says yes. But a judge said no, ruling against Panera in its bid to prevent a Mexican restaurant from moving into the same shopping mall.

Panera has a clause in its lease that prevents the White City Shopping Center in Shrewsbury from renting to another sandwich shop. Panera tried to invoke that clause to stop the opening of an Qdoba Mexican Grill.

But Superior Court Judge Jeffrey Locke cited Webster's Dictionary as well as testimony from a chef and a former high-ranking federal agriculture official in ruling that Qdoba's burritos and other offerings are not sandwiches.

The difference, the judge ruled, comes down to two slices of bread versus one tortilla.

"A sandwich is not commonly understood to include burritos, tacos and quesadillas, which are typically made with a single tortilla and stuffed with a choice filling of meat, rice, and beans," Locke wrote in a decision released last week.

In court papers, Panera, a St. Louis-based chain of more than 900 cafes, argued for a broad definition of a sandwich, saying that a flour tortilla is bread and that a food product with bread and a filling is a sandwich.

Qdoba, owned by San Diego-based Jack in the Box Inc., called food experts to testify on its behalf.

Among them was Cambridge chef Chris Schlesinger, who said in an affidavit: "I know of no chef or culinary historian who would call a burrito a sandwich. Indeed, the notion would be absurd to any credible chef or culinary historian."
nik39 11:05 PM - 10 November, 2006
Quote:
Doesnt matter what is printed, its "officialy sponsored" they should have protocols in place to make sure that kind of shit doesnt tarnish there reputation, they cant just asume that nobody makes mistakes. The reason rane/serato got all bent out of shape was because it was "officially sponsored" Im not sure exactly what officially sponsored means but it sounds like everything produced is brought to you by them.

Look at how technical they are when it came time to designing the shirts

Valid point taken.

Quote:
I asked you to "show" & "prove" and all you're doing is just talking... still.

Please upload those previous fliers so everyone can see.

I screwed up, yes, and I've admitted it.

You are claiming that I did this repeatedly, and to me, your judging my character. You're making me look shady.

So, I ask again, and prove it. Show some evidence where I've mentioned file sharing before Session 4.

tony, I told you before, I have no reason to make you look bad.

Concerning YOUR claim, that I am trying to make you look shady... please be honest (you know what I mean...):

img208.imageshack.us <- click, that was the ("RaneSSLFlyerFinal.jpg") image you have used for your latest event, session 4. At the time when I posted the information that you are supporting file sharing on your flyers thus events, I have searched the forum and came across this image's link which you have used on the promotion for session number two:

img396.imageshack.us <- click ("SSL Zen Flyer 2.jpg").

As I've said before, it looks like you were using generic flyers for your events (which absolutely makes sense, as you were doing it on a bi-weekly base - no need to print new flyers twice a month), as both links seem to be the same image (in fact they are not the same file, they are different files).

Didnt I tell you that before?! If you want to find out the threads, please go and search for them, click scratchlive.net <- here for all threads containing "SSL Zen Flyer 2.jpg" and scratchlive.net <- here for all threads containing "RaneSSLFlyerFinal.jpg".

However, again, they have been posted to promote

a. SSL session 4, and
b. SSL session 2.

I hope that answers your question, why I posted the "assumption" you were promoting filesharing not only on your latest upcoming event. Now please reconsider your claim that I am trying to make you look shady, matter of fact with that claim (although I gave you the info before why I "claimed" it) you were bad mouthing me.

Quote:
BTW --- These flyers were NEVER printed!!!

What do you want to argue about? You called those flyers in your words "e-flyers". They have the function to PROMOTE your events, by being watched by people. That counts. You used those flyers to promote, thats what they were designed for.

However, dont tell me they have never been printed - tell Serato and Rane, they need to know, not me.
DJ_Mike_Coquilla 11:18 PM - 10 November, 2006
chimichanga, nothin but love for tha deep fried burrito :) yummmmy. extra cheese and sour cream yo.
DJ_QB 11:21 PM - 10 November, 2006
hey by the way nik39 you still have yet to answer are you male or female i saw a picture of nik39 profile and it had a girls picture on it was that you? just a simple yes or no.
DJ_Mike_Coquilla 11:30 PM - 10 November, 2006
Seinfeld - NO SOUP FOR YOU!

Watchwww.youtube.com

Watchwww.youtube.com
Kool DJ Sheak One 12:35 AM - 11 November, 2006
However, a Torta is a sandwich. Burritos are an American invention. Hot dogs too.
m0rph! 12:56 AM - 11 November, 2006
I am told that the last sentence in the judge's decision read,
"A sandwich is a sandwich, but a Manwich is a meal."

I have not been able to confirm this, however... ;-)
twinsouls 2:40 AM - 11 November, 2006
I thought file sharing itself is not illigle anyway, just the files that have a copyright.???? I thought there were a lot of indipendent artist who use file sharing as a tool to promote themselves so why not support (Legal) file sharing?
AKIEM 3:16 AM - 11 November, 2006
hope someone reads this:
how about some protocols, guidelines, structure, advice, and support for officially sanctioned local Rane/Serato DJ clinics?
Clark @ Breakin-Records.com 4:24 PM - 11 November, 2006
I have socks.
DJ Michael Basic 9:05 PM - 12 November, 2006
A marriage is a paper are they fakin' or for real.
Serato
James 9:31 PM - 12 November, 2006
And 3...2.....1....Locked
Serato
James 9:32 PM - 12 November, 2006
1. Be nice to others
Serato
James 9:34 PM - 12 November, 2006
PS s42000 I *was* wondering how that c++ thing works... ;)
Serato, Forum Moderator
Sam 11:34 PM - 13 November, 2006
Tony, thank you very much for your apology... accepted without reservation.

I think the message got through - we don't support illegal activities, regardless of the intention of the person committing or condoning them.

I certainly hope that this does not mean the end of your sessions.
Sam