0% found this document useful (0 votes)
22 views32 pages

Chapter 2

Chapter two covers the basics of C++ programming, including the structure of a C++ program, the compilation process, and the use of Integrated Development Environments (IDEs). It explains the steps to create an executable file, the components of a C++ program, and the basic elements such as keywords, identifiers, literals, and comments. Additionally, it discusses data types, variables, constants, operators, and provides examples of C++ syntax and operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views32 pages

Chapter 2

Chapter two covers the basics of C++ programming, including the structure of a C++ program, the compilation process, and the use of Integrated Development Environments (IDEs). It explains the steps to create an executable file, the components of a C++ program, and the basic elements such as keywords, identifiers, literals, and comments. Additionally, it discusses data types, variables, constants, operators, and provides examples of C++ syntax and operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Chapter two

C++ Programming Basics


Structure of C++ Program

 C++ is a 3rd-generation language. These types of languages must


be translated into a machine language in order to be executed by a
CPU.

 The process of translating high-level language into machine


language is called the compilation process.
The compilation process consists of the following steps.
• edit source code -> compile -> link -> execute
(editor) (compiler) (linker) (loader)
 Program source code is entered into a file using a text editor.
 After the code has been entered, a compiler program is started that
translates the source into an object code file.
 The object code file is linked with other object code files that come with
the compiler and an executable file (or program) is created.
 In order to execute the program, the loader copies the executable file into
the memory of the computer and sends an execute command to the CPU.
C++ IDE(Integrated Development Environment)
IDE is the software that helps you write your code. Example Code::Blocks
and Dev-C++
 The complete development cycle in C++ is: Write the program, compile
the source code, link the program, and run it.
Write the program
• To write a source code, your compiler may have its own built-in text
editor, or you may be using a commercial text editor.
• The files you create with your editor are called source files, with a .CPP
extension.

Compiling
• Your source code file can't be executed, or run, as a program can.
• To turn your source code into a program, you use a compiler.
• After your source code is compiled, an object file is produced with the
extension .OBJ.
• This is still not an executable program, however, to turn this into an
executable program, you must run your linker.
Cont….
Linking
• C++ programs are typically created by linking together one or more
OBJ files with one or more libraries.
• A library is a collection of linkable files
The steps to create an executable file are :
1. Create a source code file, with a .CPP extension.
2. Compile the source code into a file with the .OBJ extension.
3. Link your OBJ file with any needed libraries to produce an executable
program.
Structure of a C++ program includes:
Cont.….
• Documentation Section: include comment parts, which is ignored by
compiler.
• The comments are used to describe the functionality of each
statement in the program to the user.
• Link section: here we can link the necessary files and libraries to
current files.
– Using #include directive we can link the necessary libraries to
current files.
Syntax: #include<file or library name>
Example: #include<iostream.h>
• Definition Section: It is possible to define symbolic constants. Symbolic
constants are normal identifiers which value cannot be altered/
modified.
Syntax: #define identifier constant
• Global declaration Section: variables declared under this section are
available throughout the program.
• Class declaration Section: defines the class declaration.
Cont.….
• Functions: function is block of instruction that is executed when it is
called form some other point of a program.
Syntax:
return type function name (){
Statement of function; }
• A function is identified by the compiler with the help of parenthesis ( )
after the function name.
• The statement inside the brace {} forms the body of the function and
specifies the task of the function.
• Return type specifies the type of data the function has to send to the
calling function after the execution.
• main ( ) function: the execution of the program starts from main
function.
• Every program must have only one main function. The initialization or
other executable statements are included with in the main function.
• Every statement under global declaration, initialization and executable
parts should be terminated with the semi colon (;). A semi colon acts
as a statement terminator like full stop in English.
C++ Sample program

For example
//C++ sample program
#include <iostream.h>
int main()
{
cout << "Hello World!\n";
return 0;
}
• Any C++ program file should be saved with file name extension “ .CPP ”.
• Type the program directly into the editor, and save the file as hello.cpp,
compile it and then run it.
• It will print the words Hello World! on the computer screen.
• The return value type for main() here is int, which means main function
will return a value to the caller.
• Cout is an object used for printing data to the screen.
• Every single statement ends with semicolon (;).
cout and cin Statements
• Cout is an object used for printing data to the screen.
• To print a value to the screen, write the word cout, followed by the insertion
operator also called output redirection operator (<<) and the object to be printed
on the screen.
• Syntax: Cout<<Object;
The object at the right hand side can be:
– A literal string: “Hello World”
– A variable: a place holder in memory
• Cin is an object used for taking or accepting an input value from the keyboard.
• To take input from the keyboard, write the word cin, followed by the input
redirection operator (>>) and the object name to hold the input value.
 Syntax: Cin>>Object
 Cin will take value from the keyboard and store it in the memory.
 Both << and >> return their right operand.
 multiple input or multiple output operations can be combined into one
statement. Example
 Cin>>var1>>var2>>var3; // three different values will be entered for the three variables
 Cout<<var1<<var2<<var3;// the values of the three variables will be printed
C++ Basic Elements
1 Keywords (reserved words)
• Reserved/Key words have a unique meaning within a C++ program.
These reserved words, must not be used for any other purposes.
• All reserved words are in lower-case letters.
C++ Basic Elements
2 Identifiers

An identifier is name associated with a function. An identifier must:

• Start with a letter or underscore

• Consist only of letters, the digits 0-9, or the underscore symbol _

• Not be a reserved word


The following are valid identifiers

Length days_in_year DataSet1 Profit95


Int _Pressure first_one first_1

The following are invalid:

days-in-year 1data int first.val


Throw my__best No## bestWish!
C++ Basic Elements
3 Literals
• Literals are constant values which can be a number, a character of a string.
• There is no identifier that identifies them. Ex. Cout<<“Hello world”;
4 Comments
• A comment is a piece of descriptive text which explains some aspect of a
program.
• Program comments are text totally ignored by the compiler and are only
intended to inform the reader.
C++ provides two types of comment delimiters:
Single Line Comment: Anything after // {double forward slash} (until the end of
the line on which it appears) is considered a comment.
–Eg:
cout<<var1; //this line prints the value of var1
Multiple Line Comment: Anything enclosed by the pair /* and */ is considered a
comment.
–Eg:
/*this is a kind of comment where
Multiple lines can be enclosed in
one C++ program */
Data Types, Variables, and Constants
Variables
• A variable is a reserved place or a symbolic name in memory location to store
information.
• Variables are used for holding data values
All variables have two important attributes:
– Data Type: a type which is established when the variable is defined. (e.g.
integer, float, character etc.).
• It describes the property of the data or variable value and the size of the
reserved memory.
– Value: a value which can be changed by assigning a new value to the
variable.
 Variable Declaration
 Declaring a variable means defining (creating) a variable.
 Create or define a variable by stating its type, followed by one or more spaces,
followed by the variable name and a semicolon.
 Syntax: Datatype Variable_Name;
E.g. int myAge; //variable used to store my age
Cont.….
 Creating/declaring more than One Variable at a Time
 You can create more than one variable of the same type in one statement
by writing the type and then the variable names, separated by commas.
 For example:
int myAge, myWeight; // two int variables
long area, width, length; // three longs
 Assigning Values to Your Variables
 assign a value to a variable by using the assignment operator (=).
Example
int Width; Width = 5;
int Width = 5;
 you can define more than one variable at a time, you can initialize more
than one variable at creation. For example:
// create two int variables and initialize them
int width = 5, length = 7;
Basic Data Types
 Data type describes the property of the data and the size of the
reserved memory
 It can be conveniently divided into numeric and character types.
• Numeric variables can further be divided into integer variables and
floating-point variables.
• Integer variables will hold only integers whereas floating number
variables can accommodate real numbers.
Type Length Range
char 8 bits 0 to 255
unsigned int 16 bits 0 to 65,535
short int 16 bits -32,768 to 32,767
Int 32 bits -32,768 to 32,767
unsigned long 32 bits 0 to 4,294,967,295
Long 32 bits -2,147,483,648 to 2,147,483,647
Float 32 bits -3.4x10-38 to 3.4x10+38
Double 64 bits -1.7x10-308 to 1.7x10+308
long double 80 bits -3.4x10-4932 to 1.1x10+4932
Bool 8 bits true or false (top 7 bits are ignored)
Cont.….
Signed and Unsigned data types
 signed integers are either negative or positive. Unsigned integers are
always positive.
 An unsigned short integer can handle numbers from 0 to 65,535.
 a signed short can only represent numbers from -32,768 to 32,767.
 The largest number you can store in an unsigned integer is twice as big as
the largest positive number you can store in a signed integer.
Example: A demonstration of the use of variables.
#include <iostream.h>
int main()
{
unsigned short int Width = 5, Length;
Length = 10;
unsigned short int Area = Width * Length;
cout << "Width:" << Width << "\n";
cout << "Length: " << Length << endl;
cout << "Area: " << Area << endl;
return 0;
}
Cont.….
Signed and Unsigned data types
 When an unsigned integer reaches its maximum value the result counter
back to 0.
Example: A demonstration of putting too large a value in a variable
1: #include <iostream.h>
2: int main()
3: {
4: unsigned short int smallNumber;
5: smallNumber = 65535;
6: cout << "small number:" << smallNumber << endl;
7: smallNumber++;
8: cout << "small number:" << smallNumber << endl;
9: smallNumber++;
10: cout << "small number:" << smallNumber << endl;
11: return 0;
12: }
Output:
small number:65535
small number:0
small number:1
Cont.….
Characters
 Character variables (type char) are typically 1 byte, enough to hold 256
values.
 A char can be interpreted as a small number (0-255) or as a member of
the ASCII set.
 The ASCII character set is a way to encode all the letters, numerals, and
punctuation marks.
 E.g In the ASCII code, the lowercase letter "a" is assigned the value 97
and the Uppercase letter “A" is assigned the value 65.
 All the lower- and uppercase letters, all the numerals, and all the
punctuation marks are assigned values between 0 and 127. Another
128 marks and symbols are reserved for use by the computer maker.
Cont.….
Operators
 C++ provides operators for composing arithmetic, relational, logical,
bitwise, and conditional expressions.
Assignment Operators
The assignment operator(=) is used for storing a value at some memory
location (typically denoted by a variable).

Operato Example Equivalent To


r
= n = 25

+= n += 25 n = n + 25

-= n -= 25 n = n - 25

*= n *= 25 n = n * 25

/= n /= 25 n = n / 25

%= n %= 25 n = n % 25

&= n &= 0xF2F2 n = n & 0xF2F2


Cont.….
Arithmetic Operators
C++ provides five basic arithmetic operators.

Operator Name Example

+ Addition 12 + 4.9 // gives 16.9


3.98 - 4 // gives -0.02
- Subtraction

* Multiplication 2 * 3.4 // gives 6.8

/ Division 9 / 2.0 // gives 4.5

% Remainder 13 % 3 //gives 1 // gives 1


Arithmetic operators.

 Except for remainder (%) all other arithmetic operators can accept a
mix of integer and real operands.
 Generally, if both operands are integers then the result will be an
integer. However, if one or both of the operands are reals then the
result will be a real (or double to be exact).
Cont.….
 Integer division always results in an integer outcome (i.e., the result is
always rounded down). Example
• 9/2 // gives 4, not 4.5!
• -9 / 2 // gives -5, not -4!
 There are also a number of predefined library functions, which perform
arithmetic operations.
Paramete Result Type
Functio
Header File r Type(s) Result
n
<stdlib.h> abs(i) int int Absolute value of i
<math.h> cos(x) float float Cosine of x (x is in
radians)
<math.h> fabs(x) float float Absolute value of x
<math.h> pow(x, y) float float x raised to the
power of y
<math.h> sin(x) float float Sine of x (x is in
radians)
<math.h> sqrt(x) float float Square root of x

<math.h> tan(x) float float Tangent of x


Cont.….
Relational Operators
 C++ provides six relational operators for comparing numeric quantities.
Relational operators evaluate to 1 ( true ) or 0 (false).

Operator Name Example


== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or Equal 5 <= 5 // gives 1
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or Equal 6.3 >= 5 // gives 1
Relational operators

• The operands of a relational operator must evaluate to a number.


• Characters also valid operands since they are represented by numeric
values, but should not be used for comparing strings.
• For example (assuming ASCII coding):
'A' < 'F’ // gives 1 (is like 65 < 70)
Cont.….
Logical Operators
C++ provides three logical operators for combining logical expression. Like the
relational operators, logical operators evaluate to 1(True) or 0(false).

Operato Name Example


r
! Logical !(5 == 5) // gives 0
Negation
&& Logical And 5 < 6 && 6 < 6 // gives 1

|| Logical Or 5 < 6 || 6 < 5 // gives 1


Logical negation
Logical is a unary operator, which negates the logical value of its single
operators
operand. If its operand is nonzero it produces 0, and if it is 0 it produces 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 nonzero value can be used to represent the logical true, whereas
only zero represents the logical false.
Cont.….
Bitwise Operators
C++ provides six bitwise operators for manipulating the individual bits in
an integer quantity.
Operator Name Example

~ Bitwise ~'\011' // gives '\366'


Negation
& Bitwise And '\011' & '\027' // gives '\001'

| Bitwise Or '\011' | '\027' // gives '\037'

^ Bitwise '\011' ^ '\027' // gives '\036'


Exclusive Or
<< Bitwise Left '\011' << 2 // gives '\044'
Shift
>> Bitwise Right '\011' >> 2 // gives '\002'
Shift
Bitwise operators
Cont.….
Bitwise Operators
Bitwise operators expect their operands to be integer quantities and treat
them as bit sequences.
 Bitwise negation is a unary operator which reverses the bits in its operands.
 Bitwise and compares the corresponding bits of its operands and
produces a 1 when both bits are 1, and 0 otherwise.
 Bitwise or compares the corresponding bits of its operands and produces
a 0 when both bits are 0, and 1 otherwise.
 Bitwise exclusive or compares the corresponding bits of its operands and
produces a 0 when both bits are 1 or both bits are 0, and 1 otherwise.
 Bitwise left shift operator(<<) produces a bit sequence equal to the left
operand but which has been shifted n bit positions to the left. Vacated bits
at either end are set to 0
 Bitwise right shift operator (>>) produces a bit sequence equal to the left
operand but which has been shifted n bit positions to the right. Vacated
bits at either end are set to 0.
Cont.….
Example:
unsigned char x = '\011';
unsigned char y = '\027';

Example Octal Value Bit Sequence


X 011 0 0 0 0 1 0 0 1
Y 027 0 0 0 1 0 1 1 1
~x 366 1 1 1 1 0 1 1 0
x&y 001 0 0 0 0 0 0 0 1
x|y 037 0 0 0 1 1 1 1 1
x^y 036 0 0 0 1 1 1 1 0
x << 2 044 0 0 1 0 0 1 0 0
x >> 2 002 0 0 0 0 0 0 1 0
Increment/decrement Operators
 The auto increment (++) and auto decrement (--) operators provide a
convenient way of, adding and subtracting 1 from a numeric variable
respectively.
int k = 5; Operator Name Example
++ Auto Increment (prefix) ++k + 10 // gives 16
++ Auto Increment (postfix) k++ + 10 // gives 15

-- Auto Decrement (prefix) --k + 10 // gives 14


-- Auto Decrement (postfix) k-- + 10 // gives 15
Increment and decrement operators

Both operators can be used in prefix and postfix form.


• When used in prefix form, the operator is first applied and the outcome
is then used in the expression.
• When used in the postfix form, the expression is evaluated first and
then the operator applied.
Precedence of Operators
• The order in which operators are evaluated in an expression is
significant and is determined by precedence rules.
• These rules divide the C++ operators into a number of precedence
levels.
For example
a =b + c * d
• c * d is evaluated first because * has a higher precedence than + and =.
The result is then added to b because + has a higher precedence than =,
and then = is evaluated.

a = (b + c) * d
Simple Type Conversion
• A value in any of the built-in types can be converted (type-cast) to any
of the other types. For example:
(int) 3.14 // converts 3.14 to an int to give 3
(long) 3.14 // converts 3.14 to a long to give 3L
(double) 2 // converts 2 to a double to give 2.0
(char) 122 // converts 122 to a char whose code is 122
(unsigned short) 3.14 // gives 3 as an unsigned short
Explicit type conversion: are unary (i.e., take one operand) and appear
inside brackets to the left of their operand.
E.g int (3.14) // same as: (int) 3.14
Implicit type conversion: This happens when values of different types are
mixed in an expression.
e.g double d = 1; // d receives 1.0
int i = 10.5; // i receives 10
i = i + d; // means: i = int(double(i) + d)
Statements

Statements represent the lowest-level building blocks of a program. C++


provides different forms of statements for different purposes.
 Declaration statements are used for defining variables.
 Assignment-like statements are used for simple, algebraic
computations.
 Loop statements are used for specifying computations which need to
be repeated until a certain logical condition is satisfied.
 Flow control statements are used to divert the execution path to
another part of the program.
The block statement
• A block begins with an opening brace ({) and ends with a closing brace (}).
• Every statement in the block must end with a semicolon, the block itself
does not end with a semicolon.
Syntax:
{
[<Declarations>].
<List of statements/statement block>.
}
The Assignment statement(=)
Syntax:
<Variable Identifier> = < expression>;
• The <expression> is evaluated and the resulting value is stored in the memory
space reserved for <variable identifier>.
Eg: - int x,y ;
x=5;
y=x+3;
x=y*y;
t w o
t e r
h a p ?
f c s ? ?
d o io n
E n e s t
Qu

Prepared By: Getie B.

You might also like