• Log in or sign up for an account here: https://www.sythe.org/login

C++ Introduction

Quality

Apprentice
Joined
Jan 24, 2007
Sythe Gold
0
Messages
680
Location
Australia, Sydney
Introduction To Programming In C++

 What is C++?

C++ is a programming language that evolved from the C programming language. Except for a few minor details, C++ includes all of the C programming language, but also offers extensions for object oriented programming.

 Streams

When you think of the word stream, you would usually picture flowing water in the ground. In C++, a stream means a flow of bytes. A byte is a unit of storage, capable of holding a single character. So a stream in C++, gets bytes of information from a source (Eg. input from the keyboard) and delivers the bytes to a destination (Eg. output on the screen).

 The cout stream

C++ has a standard output stream called cout. The destination of this stream is usually the screen. To direct data into the stream, you would use the output operator <<.

&#61476; EXAMPLE 1: A basic C++ program
Code:
#include <iostream.h>

main()
{
	cout << “Hello World”;
}
In the example above, the text “Hello World” is directed via << to the cout stream, and output to the screen. Note that strings of text need to be enclosed in inverted commas, “ ”, and many lines require a semicolon at the end, ;.

Note also that the line #include <iostream.h> needs to be included in every program. The header file iostream.h contains an important definition for the cout stream.

&#61476; Comments

A comment is a piece of text in a program that attempts to explain what is going on at that point in the program. Special symbols are used to mark comments in a program so the compiler knows to ignore that text when compiling the code and checking for errors.

In C++, there are two ways of defining comments. Any text enclosed between the symbols /* and */ is a comment. Anything on a single line after a // is also a comment.

&#61498; EXAMPLE 1 with COMMENTS:
Code:
/*
	This program displays the greeting
	Hello World on the screen
*/

#include <iostream.h>  

main()
{
	cout << “Hello World”;  // Output greeting to the screen
}

Try typing this code into the C++ Program. Save it as: example1.cpp
Run the program.


&#61476; Variables

A variable is a named location in memory, in which you can store a value. Before you can use a variable in a program, you need to declare it’s name, as well as it’s data type.

&#61476; Data Types

The data type of a variable determines what kind of data can be stored in it. There are three basic types used in C++:

Data Type Definition Examples
char character / letter a, B, z
int integer / whole number 5, 39, 1234
float numbers with decimal places 2.75, 0.003




&#61476; Declaring Variables

To declare a variable, you specify it’s type, followed by the name of the variable:

char letter; // declares a variable named letter, of type char (character)

You can also declare two or more variables of the same type on the one line, by separating them with commas:

int numb1, numb2, numb3; // declares three variables, a, b and c all of type int (whole number)

&#61476; Naming Variables

The following rules apply when naming your variables:
• The first character must be either an: uppercase letter (A..Z), lowercase letter (a..z) or an underscore ( _ ).
• The rest of the characters can be made up of uppercase letters, lowercase letters, the underscore, or a digit (0..9).
• Variable names are case sensitive. So the variables Num1 and NUM1 are regarded as two different variables.
• You can’t have any spaces in your variable names. So:
o TotalPay, totalpay, totalPay, Total_Pay, total_Pay (etc) are all fine
o Total Pay, total pay (etc) will not compile properly due to the space

&#61476; Initializing Variables

You can assign a value to a variable when you declare it. This is called initializing. Example:

float numb1 = 2.5; // declares a variable called numb1, of type float, and assigns the value 2.5 to it.

&#61498; EXAMPLE 2: Declaring and initializing variables, and sending multiple items to cout
Code:
#include <iostream.h>

main()
{
	char letter = ‘A’;  // the character A needs to be in single quotation marks
	int i = 5;
	float f = 3.75;

	cout << “letter = “ << letter << “ i = “ << i  << “ f = “ << f;
}

Output given:
letter = A i = 5 f = 3.75

&#61476; The cin stream

The standard input stream for C++ is cin. It usually gets it’s data from the keyboard. The operator >> is used to direct data flowing in on this stream into program variables.

&#61498; EXAMPLE 3: The cin stream
Code:
#include <iostream.h>

main()
{
	char letter;

	cin >> letter;  // The character entered into the keyboard flows into the variable letter
	cout << “You entered the character “ << letter;
}
&#61498; EXAMPLE 4: Using cin to read multiple items of various data types
Code:
#include <iostream.h>

main()
{
	char letter;
	int i;
	float f;

	cout << “Enter a character, then an integer and then a real number, separated by spaces: “;
	cin >> letter >> i >> f;  // Read different data types all on one line
	cout << “You entered “ << letter << “, “ << i << “, “ << f;
}
Sample Input: k 4 6.7
Sample Output: You entered k, 4, 6.7


&#61476; Operators

An operator is a symbol that is used to signify that some kind of operation is to be performed on data elements. Some of the operators available in C++ are as follows:

The ASSIGNMENT operator (make a variable equal to something)
Operation Symbol Example
Assignment = X=5

The UNARY ARITHMETIC operators (meaning operations performed on only one variable)
Operation Symbol Example
Unary plus + +a
Unary minus - -a

The BINARY ARITHMETIC operators (where operations are performed on two variables)
Operation Symbol Example
Addition + a + b
Subtraction - a – b
Multiplication * a * b
Division / a / b
Modulus (remainder) % a % b

The ARITHMETIC ASSIGNMENT operators
Operation Symbol Example Equivalent To
Add Assign += a += b a = a + b
Subtract Assign -= a -= b a = a - b
Multiply Assign *= a *= b a = a * b
Divide Assign /= a /= b a = a / b

&#61476; Newline

To move the screen cursor to a new line (usually after you have output text) you can use \n or endl. Example:

cout << “Line 1 of text”; cout << “Line 1 of text\n”; cout << “Line 1 of text” << endl;
cout << “Line 2 of text”; cout << “Line 2 of text\n”; cout << “Line 2 of text” << endl;

Output given: Output given: Output given:
Line 1 of textLine 2 of text_ Line 1 of text Line 1 of text
Line 2 of text Line 2 of text
_ _

&#61498; EXAMPLE 5: Using Operators and Newline
Code:
#include <iostream.h>

main()
{
	int numb1=4, numb2=5, numb3=6, result1, result2, result3;

	result1 = numb1 + numb2;
	cout << “result1 is “ << result1 << “\n”;
	result2 = numb2 * numb1;
	cout << “result2 is “ << result2 << “\n”;
	result3 = numb3 / numb1;
	cout << “result3 is “ << result3 << endl;
	result2 -= result1;
	cout << “result2 is “ << result2;
}
&#61476; Declaring Constants

To get the compiler to treat a variable as a constant (a value that doesn’t change), you can insert the word const in front of a variable declaration. Any attempt to change the value in the program will result in an error.

For example, the following statement defines an unchangeable float variable called PI, as in the mathematical constant &#61520;. It is permanently set to 3.14159 throughout the whole program.

const float PI = 3.14159;

&#61498; EXAMPLE 6: Using constants
Code:
#include <iostream.h>

main()
{
	const float PI = 3.14159;
	float diameter;

	cout << “Enter the diameter of the circle: “;
	cin >> diameter;
	cout << “Circumference = “ << diameter * PI;
}
&#61476; BODMAS and Parentheses

When doing calculations, you should always remember the rules of BODMAS, where brackets, also called parentheses, are evaluated first. To use parentheses in your calculations in C++, simply use ( ).



&#61476; Comparison Operators

Most programs need to make decisions. These Comparison Operators allow the programmer to test various variables against other variables or values.
Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
= = equal to
! = not equal to


&#61476; if statements

Comparison Operators are often used to form conditions in if statements. The if statement is used to perform a comparison and potentially change the flow of the program by following another path / statement. In C++, the general form of an if statement is as follows:

if (condition)
statement;

If the condition evaluates to true, the statement will be executed. If false, the statement will not.

&#61498; EXAMPLE 7: If Statement
Code:
#include <iostream.h>

main()
{
	int age;

	cout << “Please enter your age: “;
	cin >> age;
	if (age > 17)  //  condition
		cout << “You are an adult”;  // statement to follow if condition is true
}

The statement part of an if statement may consist of a number of statements enclosed by curly braces:
if (condition)
Code:
{
	statement;
	statement;
	statement;
}

&#61476; if else statements

An if statement can also be followed by an else statement. The general format is:

if (condition)
statement1;
else
statement2;

If the condition evaluates to true, statement1 will be executed. Otherwise (if false), statement2 will be executed.

&#61498; EXAMPLE 8: if else statement
Code:
#include <iostream.h>

main()
{
	int age;
	
	cout << “Please enter your age: “;
	cin >> age;
	if (age >= 18)  //  condition
		cout << “You are an adult”;  // statement to follow if condition is true
	else
		cout << “You are not an adult yet”;  // statement to follow if condition is false
}
&#61476; Logical OR Operator (||)

The logical OR operator || can be used between two conditions: if ( (condition1) || (condition2) )
statement;

The statement will be executed if: condition1 is true, or if condition2 is true, or both conditions are true. If both conditions are false, the statement will not be executed.

&#61498; EXAMPLE 9: Logical OR Operator
Code:
#include <iostream.h>

main()
{
	int n;
	cout << “Please enter a number in the range (1...10): “;
	cin >> n;
	if ( (n < 1) || (n > 10) )
		cout << “Number is not in the required range”;
	else
		cout << “Number is in the required range”;
}

&#61476; The Logical AND Operator (&&)

The logical AND operator && can be used between two conditions: if ( (condition1) && (condition2) )
statement;

The statement will be executed if: condition1 is true and if condition2 is true, otherwise (if both conditions are false), the statement will not be executed.

&#61498; EXAMPLE 10: Logical AND Operator
Code:
#include <iostream.h>

main()
{
	int n;
	cout << “Please enter a number in the range (1...10): “;
	cin >> n;
	if ( (n >= 1) && (n <= 10) )
		cout << “Number is in the required range”;
	else
		cout << “Number is not in the required range”;
}
&#61476; The NOT Operator (!)

The NOT operator ! is used for negation:

if !(a == b)
statement;

The statement will be executed if a is not equal to b. The compiler will check firstly if a is equal to b (==) and then will negate the outcome(!) (so if it was true make it false, or if it was false make it true).

The Not Equal To (!=) operator could also be used instead of above: if (a !=b) statement;


&#61476; The else if statement

An if statement can also be followed by an else if statement, then an else. The general format is:

if (condition1)
statement1;
else if (condition2)
statement2;
else
statement3;

If condition1 evaluates to true, statement1 will be executed. Otherwise (if false), the compiler will check if condition2 evaluates to true. If so, then statement2 will be executed, otherwise (if also false), then statement3 will be executed.

&#61498; EXAMPLE 11: else if statement
Code:
#include <iostream.h>

main()
{
	int age;
	
	cout << “Please enter your age: “;
	cin >> age;
	if (age >= 18)  //  condition1
		cout << “You are old enough to get your license”;  // statement to follow if condition1 is true
	else if (age >=16) // condition2
		cout << “You are old enough to get your learners permit”;  // statement to do if cond2 is true
	else
		cout << “You are not old enough to be behind the wheel of a car yet”;  // do if others are false
}

&#61476; The isalpha() and isdigit() macros

The isalpha(value) macro returns true if value is a letter (A..Z, a..z), otherwise it returns false.

The isdigit(value) macro works in the same way, returning true if value is a digit (0..9), otherwise false.

Both macros require the header file ctype.h to be included.

&#61498; EXAMPLE 12: isdigit() function


&#61476; The isupper() and islower() macros

The isupper(value) macro returns true if value is an uppercase letter (A..Z), otherwise it returns false.

The islower(value) macro works in the same way, returning true if value is a lowercase letter (a..z), otherwise it returns false.

Both macros require the header file ctype.h to be included.

Example:
Code:
	if ( islower(value) )
		cout << “The character you entered is a lowercase letter”;
	else
		cout << “The character you entered is not a lowercase letter”;
&#61476; The random() function

The random() function returns a random integer (whole number) between 1 and n-1. So:
value = random(10); // puts a random number in the range 0 – 9 in value
value = random(10)+1; // puts a random number in the range 1 – 10 in value

The header file stdlib.h must be included in any program that uses the random() function.

&#61476; The randomize() function

The randomize() function initializes the random number generator. A call to the randomize() function should be made at the beginning of any program that uses the random function.

The randomize() function uses the time() function to initialize the random number generator, so the header file time.h should be included in any program that uses the randomize() function.



&#61498; EXAMPLE 13: Getting a random number using random()
Code:
#include <iostream.h>
#include <stdlib.h>
#include <time.h>

main()
{
	int value;

	randomize();
	value = random(50);
	cout << “The random number is” << value;
}
&#61476; The rand() function

The rand() function works similarly to the random() function. It still requires the use of randomize() and stdlib.h, but not time.h.

value = rand() %10; // puts a random number in the range 0 – 9 in value
value = 1 + rand() %10; // puts a random number in the range 1 – 10 in value

This is probably the better of the two functions to use, as it is more common.

&#61498; EXAMPLE 14: Getting a random number using rand()
Code:
#include <iostream.h>
#include <stdlib.h>

main()
{
	int value;

	randomize();
	value = rand() % 10;
	cout << “The random number is” << value;
}

&#61476; Character Array

char word; This definition would allow one character to be stored in the variable word.

char word[20]; This definition allows for a string of text to be stored in word, that can be 19 characters long. One character needs to store the terminating null character, but don’t worry about that for now. Just remember it as n-1 characters.



&#61476; The strrev() function

The strrev() function reverses a string of text.

If the word is “fred”.

cout << strrev(word);

The output would be “derf”

The string.h header file must be included.

&#61498; EXAMPLE 15: strrev() and character array
Code:
#include <iostream.h>
#include <string.h>

main()
{
	char word[20];  // variable word can store a string up to 19 chars long

	cout << “Please enter a word: “;
	cin >> word;
	cout << “The word in reverse is: “ << strrev(word);
}


&#61476; Manipulators and Format Flags

Now that you have learnt a number of the basic C++ functions, it’s time to learn how to manipulate and format the output to the screen, to make it easier to read and look more visually appealing.

Manipulators are used to format input or output to streams. The following table contains some commonly used manipulators.

MANIPULATORS
Manipulators Purpose
setiosflags(ios:: flag) Sets the specified input/output format flag (see table below)
resetiosflags(ios:: flag) Resets the specified input/output format flag (see table below)
setprecision(n) Sets the number of decimal places to n
setw(n) Next item will be printed in a field n characters wide
endl Produces a line feed

The manipulators setiosflags() and resetiosflags() are used to set or rest format flags. Some commonly used format flags are listed in the following table.

FORMAT FLAGS
Manipulators Purpose
Left Output will be left justified
Right Output will be right justified
Fixed Floating point numbers will be displayed in decimal format with a fixed number of decimal places
Showpoint Floating point numbers will be displayed with a decimal point. For example, if the fixed flag has been set, and the setprecision() manipulator has been used to set the precision to 2 decimal places, a floating point variable with the value 50 would be displayed as 50.00 instead of 50
skipws White space (spaces, tabs, linefeeds, etc) will be skipped when inputting data elements

The header file iomanip.h must be included in any program that uses output manipulators.

&#61498; EXAMPLE 16: setw, setiosflags(ios:: right), endl
Code:
#include <iostream.h>
#include <iomanip.h>

main()
{
	int a = 10, b = 20, c = 30;
	
	cout << a << b << c;
	cout << endl;
	cout << a << setw(5) << b << setw(5) << c;
	cout << endl;
	cout << setiosflags(ios:: right);
	cout << setw(5) << a << setw(5) << b << setw(5) << c;
}


&#61498; EXAMPLE 17: setiosflags(ios:: fixed), setprecision(n), setiosflags(ios:: showpoint)
Code:
#include <iostream.h>
#include <iomanip.h>

main()
{
	float price, rate, discount;

	cout << "Please enter the price: ";
	cin >> price;
	cout << "Please enter the discount rate as a percentage (Eg. 7.5): ";
	cin >> rate;
	discount = price * rate / 100;
	cout << endl;
	cout << "Discount = $"	<< setiosflags(ios:: fixed)
				<< setprecision(2)
				<< setiosflags(ios:: showpoint)
				<< discount << endl;
	cout << "Discount price = $" << price - discount;
}
Output Given:
Please enter the price: 50
Please enter the discount rate as a percentage (Eg. 7.5): 10

Discount = $5.00
Discount price = $45.00

&#61476; The gotoxy() function

The gotoxy() function moves the cursor to the specified position on the screen.

gotoxy(20,2); // Positions the cursor 20 spaces across the screen (horizontally), 2 lines down (vertically).

The header file conio.h needs to be included.

&#61476; The clrscr() function

The clrscr() function can be used to clear the screen. In many programs it is not necessary to clear the screen, but when you are specifically manipulating and formatting the output it is a good idea. The header file conio.h needs to be included.

&#61498; EXAMPLE 18: gotoxy() and clrscr()
Code:
#include <iostream.h>
#include <conio.h>

main()
{
	clrscr();
	gotoxy(29,3);
	cout << "The HELLO WORLD program";
	gotoxy(29,4);
	cout << "***********************"; // Note:  24 asterisks
	gotoxy(35,12);
	cout << "HELLO WORLD!" << endl;
}


Resources: School Sites and School Textbooks.

I used this as an assignment awhile ago and reworded a lot of it from various websites just putting this out. Just found it the other day and thought why not. Haven't dont any of this for about a year. Did acceleration computing and had to do it but stopped it now. This might have changed a bit as it was completed awhile ago.
 
pro man prooooo
 
Runescape Gamblingrunescape gambling
Back
Top