CHAPTER 2
C++ Basics
STRUCTURE OF C++ PROGRAM
• 1. Comment
• There are two comment in C++ program: - Single line comment (//) and Multiple line
comment. (/*)
• They do not have any effect on the behavior of the program.
• The programmer can use them to include short explanations or observations within
the source code itself. In this case, the line is a brief description of what our program
is.
• 2. #include <iostream>
• Lines beginning with a hash sign (#) are directives for the preprocessor.
• They are not regular code lines with expressions but indications for the compiler's preprocessor.
• Preprocessor directive is an instruction given to the compiler before the execution of actual program.
• In this case the directive #include <iostream> tells the preprocessor to include the iostream standard file.
• They are lines read and processed by the preprocessor and do not produce any code by themselves.
• Preprocessor directives must be specified in their own line and do not have to end with a semicolon (;).
• # i n c l u d e is a header file library.
• This specific file (iostream) includes the declarations of the basic standard input-output library in C++, and
it is included because its functionality is going to be used later in the program.
• 3. Using namespace std;
• All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std;
• using namespace std; means that we can use names for objects and variables from
the standard library.
• 4. int main ()
• The main function is the point by where all C++ programs start their execution,
independently of its location within the source code.
• It does not matter whether there are other functions with other names defined before or
after it - the instructions contained within this function's definition will always be the first
ones to be executed in any C++ program.
• It is essential that all C++ programs have a main function.
• The word main is followed in the code by a pair of parentheses (()).
• int main (): This is called a function. Any code inside its curly brackets { } will be execute
• 5. Like cout << "Hello World!";
• This line is a C++ statement. A statement is a simple or compound expression that can
actually produce some effect. In fact this statement performs the only action that
generates a visible effect in our first program.
• Notice that the statement ends with a semicolon character (;). This character is used to
mark the end of the statement and in fact it must be included at the end of all expression
statements in all C++ programs (one of the most common syntax errors is indeed to
forget to include some semicolon after a statement). Note that cout is included within the
std namespace of the iostream standard file and is used to display characters in the
standard output stream like the computer monitor.
• 6. return 0;
• The return statement causes the main function to finish.
• A return code of 0 for the main function is generally interpreted as the program
worked as expected without any errors during its execution.
• This is the most usual way to end a C++ console program.
• The program has been structured in different lines in order to be more readable, but
in C++, we do not have strict rules on how to separate instructions in different lines.
For example, instead of
• int main ()
• {
• cout << “Hello World!";
• return 0;
• }
• We could have written:
• int main () {cout << "Hello World!"; return 0 ;}
• All in just one line and this would have had exactly the same meaning as the previous
code.
• Identifiers
• Programming languages use special symbols called identifiers to name such programming entities as variable, constants and function rules.
• In simple terms identifiers are names of variables, constants functions and other entities in the program.
• An identifier must:
• Start with a letter ( A to Z) or underscore ( _ )
• Consist only of letters, the digits 0-9, or the underscore symbol
• Not be a reserved word
• Uppercase and lowercase characters are distinct (like ≠ Like) so this lead to C++ is case-sensitive.
• Literals are constant values which can be a number, a character of a string.
• Variables and Constants
VARIABLES AND CONSTANTS
Variables
• ƒa variable is a reserved place in memory to store information in.
• ƒVariables are used for holding data values so that they can be used in various computations in a program.
• A variable is a symbolic name for a memory location in which data can be stored
• The variables are created in RAM. RAM is temporary memory. So data stored in a variable is also
temporary.
• Variable names cannot also be the same as keywords used by C++.
• The data stored in the variable is automatically removed when program ends.
• Variables must be declared before used.
• All variables have three important properties:
• All variables have three important properties:
• Data Type: a type which is established when the variable is defined. (E.g. integer, real,
character etc.)
• Data type describes the property of the data and the size of the reserved memory.
• Name: a name which will be used to refer to the value in the variable. A unique identifier
for the reserved memory location
• Value: a value which can be changed by assigning a new value to the variable.
• Data type describes your data like what form of data you want to create.
• It may be integer, character
SIGNED AND UNSIGNED
• Signed integers are either negative or positive. Unsigned integers are always
positive. Because both signed and unsigned integers require the same number of
bytes, the largest number (the magnitude) that can be stored in an unsigned integer
is twice as the largest positive number that can be stored in a signed integer.
Declaring Variables
• Variables can be created in a process known as declaration.
• Syntax: Datatype Variable_Name;
E.g. int myAge; //variable used to store my age
INITIALIZING VARIABLES.
• When a variable is assigned a value at the time of declaration, it is called variable initialization.
• This is identical with declaring a variable and then assigning a value to the variable immediately
after declaration.
• The syntax of initialized a variable is:
• Data_type variable_name = value;
• The equal sign “=” is used to initialized a variable.
• Examples: int myage;
• int n = 100;
• float = 3.65;
SCOPE OF VARIABLES
• Scope of a variable is the boundary or block in a program where a variable can be accessed. The
boundary or block is identified by the left and right French brackets.
• In C++, we can declare variables anywhere in the source code. But we should declare a variable
before using it no matter where it is written.
• Global variables: are variables that can be referred/accessed anywhere in the code, within any
function, as long as it is declared first. A variable declared before any function immediately after the
include statements are global variables.
• Local Variables: the scope of the local variable is limited to the code level or block within which they
are declared.
• Boolean variables are set to either true or false. Expressions that have a true or false value are called
Boolean expressions.
EXAMPLE
• /*this program uses Boolean variables.*/
• #include using namespace std;
• int main ()
• { bool boolValue ;
• boolValue = true ;
• cout << boolValue << endl ;
• boolValue = false ;
• cout << boolValue << endl ;
• return 0 ;
• }
• Program out put
• 1
• 0
CHARACTER DATA TYPE
• A variable of the char data type holds only a single character.
• Example:
• // this program uses character constants.
• #include using namespace std ;
• int main ()
• { char letter; letter = 'A';
• cout << letter << '\n’;
• letter = 'B';
• cout << letter << '\n'; return 0 ;
• }
• Program output
• A
• B
ESCAPE SEQUENCE IN C++
\n Newline
\t Horizontal tab
\a Alarm
\b Backspace
\r Return
\\ Backslash
\’ Single quote
\” Double quote
\? Question mark
CONSTANTS
• A constant is any expression that has a fixed value.
• Constant is a data item whose value cannot change during the programs execution.
• It may contains integer constants, string constants (i.e., string literals), and a variable.
• Constants must be initialized when they are created by the program, and the
programmer can’t assign a new value to a constant later.
• C++ provides two types of constants: literal and symbolic constants.
CONT…
• Literal constant: is a value typed directly into the program wherever it is needed.
• E.g.: int num = 83;
• 83 is a literal constant in this statement:
• Symbolic constant: is a constant that is represented by a name, similar to that of a variable.
But unlike a variable, its value can’t be changed after initialization.
• E.g.: Int studentPerClass =15;
• students = classes * studentPerClass;
• studentPerClass is a symbolic constant having a value of 15. And 15 is a literal constant
directly typed in the program.
OPERATORS
• An operator is a symbol that makes the machine to take an action.
• C++ provides several categories of operators, including the following:
1. ASSIGNMENT OPERATOR
• The assignment operator causes the operand on the left side of the assignment statement to have its value changed to the value on the right side of the statement.
• Syntax: Operand1=Operand2;
• Operand1 is always a variable
• Operand2 can be one or combination of:
• • A literal constant: E.g: x=12;
• • A variable: E.g: x=y;
• • An expression: Eg: x=y+2;
• Compound assignment operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=).
• Compound assignment operator is the combination of the assignment operator with other operators like arithmetic and bit wise operators.
• E.g.: value += increase; is equivalent to value = value + increase;
• a -= 5; is equivalent to a = a – 5;
• a /= b; is equivalent to a = a / b;
2. ARITHMETIC OPERATORS (+, -, *, /, %)
• Except for remainder or modulo (%), all other arithmetic operators can accept a mix of integers and real operands.
• Integer division always results in an integer outcome.
• Division of integer by integer will not round off to the next integer
• E.g.: 9/2 gives 4 not 4.5
• -9/2 gives -4 not -4.5
•
• The module (%) is an operator that gives the remainder of a division of two integer values. For instance, 13 % 3 is
calculated by integer dividing 13 by 3 to give an outcome of 4 and a remainder of 1; the result is therefore 1.
•
• E.g.: a = 11 % 3 a is 2
3. RELATIONAL OPERATOR (==, !=, > , =,
<=).
• In order to evaluate a comparison between two expressions, we can use the relational
operator.
• The result of a relational operator is a bool value that can only be true or false
according to the result of the comparison.
•
• E.g.: (7 = = 5) would return false or returns 0
• (5 > 4) would return true or returns 1
4. LOGICAL OPERATORS (!, &&, ||):
• Logical negation (!) is a unary operator, which negates the logical value of its
operand. If its operand is non zero, it produce 0, and if it is 0 it produce 1.
• Logical AND (&&) produces 0 if one or both of its operands evaluate to 0 otherwise it
produces 1.
• Logical OR (||) produces 0 if both of its operands evaluate to 0 otherwise, it produces
1.
• In general, any non-zero value can be used to represent the logical true, whereas
only zero represents the logical false.
INCREMENT/DECREMENT OPERATORS: (++)
AND (--)
• The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively, adding and
subtracting 1 from a numeric variable.
• Prefix and Postfix:
•
• The prefix type is written before the variable. Eg (++ y), whereas the postfix type appears after the variable name (y++).
• The prefix operator is evaluated before the assignment, and the postfix operator is evaluated after the assignment.
• E.g. int k = 6 ;
• (auto increment prefix) y= ++k + 10; //gives 17 for y
• (auto increment postfix) y= k++ + 10; //gives 16 for y
• (auto decrement prefix) y= --k + 10; //gives 15 for y
• (auto decrement postfix) y= k-- + 10; //gives 16 for y