0% found this document useful (0 votes)
25 views

CH 2

The document discusses the structure and components of a basic C++ program. It covers: 1. The main components of a C++ program include preprocessor directives, comments, and the main function which contains the starting, body, and return of the function. 2. Preprocessor directives like #include are used to include header files. The main function is where program execution begins. 3. Variables are used to store and manipulate data in a program. They have a type and value, and must be declared before use. Basic variable types in C++ include integers, characters, and floating-point numbers.

Uploaded by

Firomsa Dine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

CH 2

The document discusses the structure and components of a basic C++ program. It covers: 1. The main components of a C++ program include preprocessor directives, comments, and the main function which contains the starting, body, and return of the function. 2. Preprocessor directives like #include are used to include header files. The main function is where program execution begins. 3. Variables are used to store and manipulate data in a program. They have a type and value, and must be declared before use. Basic variable types in C++ include integers, characters, and floating-point numbers.

Uploaded by

Firomsa Dine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Chapter Two

C++ Basics
Structure of C++ Program
A C++ program has the following structure

[Preprocessor directives] #include<iostream>


[Comments] // My first program in C+
[The main function] +
 [Starting of main function] Using namespace std;
int main()
 [Body of function]
{
 [Return the function]
Cout<<“Hello World”;
 [End of the function] Return 0;
}
// my first program in C++
 This is a comment line. All lines beginning with two slash signs (//) are considered

comments and do not have any effect on the behavior of the program.

#include <iostream>

 Lines beginning with a hash sign (#) are directives for the preprocessor.

 In this case the directive #include <iostream> tells the preprocessor to include the

iostream standard file.


 #include is a preprocessor directive that tells the preprocessor to include header files in the program

 This specific file (iostream) includes the declarations of the basic standard input-output

library in C++
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.

 This line is very frequent in C++ programs that use the standard library

 Namespaces are used to organize code into logical groups and to prevent name
collisions that can occur especially when your code base includes multiple
libraries.
 int main ()

 This line corresponds to the beginning of the definition of the main


function.

 The main function is the point by where all C++ programs start their
execution, independently of its location within the source code.

 The word main is followed in the code by a pair of parentheses (()). That is
because it is a function declaration

 Right after these parentheses we can find the body of the main function
enclosed in braces ({}).
Cont..
 cout << "Hello World!"; This line is a C++ statement.

 A statement is a simple or compound expression that can actually produce


some effect.

 cout represents the standard output stream in C++

 The meaning of the entire statement is to insert a sequence of characters (in


this case the Hello World sequence of characters) into the standard output
stream (which usually is the screen).

 cout is declared in the iostream standard file within the std namespace

 Notice that the statement ends with a semicolon character (;)


return 0;

The return statement causes the main function to finish.

Return may be followed by a return code (in our example is


followed by the return code 0)

A return code of 0 for the main function is generally interpreted


as the program worked as expected without any errors during
its execution.
IDE
An integrated development environment (IDE) is a software
application that provides comprehensive facilities to computer
programmers for software development.

An IDE normally consists of a source code editor, build automation


tools, and a debugger.

is a software application that combines all of the features and tools
needed by a software developer.
C++ Program Development Process (PDP)
 C++ programs typically go through six phases before they can be executed. These

phases are:

1. Edit: The programmer types a C++ source program, and makes correction, if

necessary. Then file is stored in disk with extension (.cpp).

2. Pre-Processor: Pre-processing is accomplished by the preprocessor before

compilation

3. Compilation: Converting the source program into object-code.

4. Linking: A linker combines the original code with library functions to produce

an executable code.

5. Loading: The loader loads the program from the disk into memory

6. Execution: CPU Executes the program, residing in memory


Keywords (reserved words)

Reserved/Key words have a unique meaning within a C++


program

These symbols, the reserved words, must not be used for any
other purposes

All reserved words are in lower-case letters

Example:- bool, case, break, auto, catch, char, delete, int, void, if,
…., float etc…
Identifiers

An identifier is name associated with a function or data object


and used to refer to that function or data object. 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

For the purposes of C++ identifiers, the underscore symbol, _,


is considered to be a letter.
Comments

 A comment is a piece of descriptive text which explains some aspect


of a program.

 Program comments are totally ignored by the compiler and are only
intended for human readers

 C++ provides two types of comment delimiters:

 Anything after // (until the end of the line on which it appears) is


considered a comment

 Anything enclosed by the pair /* and */ is considered a comment


Input/ Output Statements

 The most common way in which a program communicates with the outside world
is through simple, character-oriented Input/ Output (IO) operations.

 C++ provides two useful operators for this purpose

 cin >> for input and


 cout<< for output

Example

cin>>a;

cout<<“welcome to programming” ;
Variables

 A variable is a symbolic name for a memory location in which data can be


stored and subsequently recalled.

 Variables are used for holding data values so that they can be utilized in
various computations in a program.

 All variables have two important attributes:

 A type, which is, established when the variable is defined (e.g., integer,
float, character)
 A value, which can be changed by assigning a new value to the
variable
Variable Declaration
 Declaring a variable means defining (creating) a variable

 You create or define a variable by stating its type, followed by one or more
spaces, followed by the variable name and a semicolon.

 The variable name can be virtually any combination of letters, but cannot
contain spaces and the first character must be a letter or an underscore

Example:-

int myAge;

 IMPORTANT- Variables must be declared before used!

 Uppercase and lowercase letters are considered to be different


Creating 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

 myAge and myWeight are each declared as integer variables.

 The second line declares three individual long variables named area, width,
and length.

 However keep in mind that you cannot mix types in one definition statement
Variable initialization
 You assign a value to a variable by using the assignment operator (=)

 Thus, you would assign 5 to Width by writing

 int Width;

 Width = 5;

 You can combine these steps and initialize Width when you define it by writing

 int width = 5;
 Just as 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;


VARIABLE SCOPE

A scope is a region of the program and broadly


speaking there are two places, where variables can be
declared:
 Inside a function or a block which is called local variables,

 Outside of all functions which is called global variables.


Local Variables
 Variables that are declared inside a function or block are local
variables
 They can be used only by statements that are inside that function or
block of code
 Following is the example using local variables:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables

Global variables are defined outside of all the functions,

usually on top of the program

Following is the example using global variables:


#include <iostream>
using namespace std;

int g = 20; // Global variable declaration:

int main ()
{
int g = 10; // Local variable declaration:

cout << g;
return 0;
}
Basic Data Types

 When you define a variable in C++, you must tell the compiler what kind of variable
it is: an integer, a character, or …….

 Several data types are built into C++.

 The varieties of data types allow programmers to select the type appropriate to the
needs of the applications being developed

 Basic (fundamental) data types in C++ 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
C++ data types and their ranges

Type Size Values/ranges


unsigned short int 2 bytes 0 to 65,535
short int(signed short 2 bytes -32,768 to 32,767
int)
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long 4 bytes -2,147,483,648 to 2,147,483,647
int)
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
Char 1 byte 256 character values
Float 4 bytes 3.4e-38 to 3.4e38
Double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932
Type int

 represent integers or whole numbers

 Some rules to follow


 Plus signs do not need to be written before the number

 Minus signs must be written when using negative #’s

 Decimal points cannot be used

 Commas cannot be used

 Leading zeros should be avoided

 Signed - negative or positive

 Unsigned - positive

 Short

 Long
Type double, float

 used to represent real numbers

 many programmers use type float

 avoid leading zeros, trailing zeros are ignored

 long double

Type char

 used to represent character data


 a single character which includes a space

 1 byte, enough to hold 256 values

 Must be enclosed in single quotes eg. ‘d’

 Escape sequences treated as single char


Cont..
‘\n’ newline
‘\’’ apostrophe
‘\”’ double quote
‘\t’ tab
Type String

Used to represent textual information

String constants must be enclosed in double quotation


marks eg. “Hello world!”
empty string “”

new line char or string “\n”

“the word \”hello\”” (puts quotes around “hello” )

The following program reads the four different data type


inputs and outputs listed on the above.
#include<iostream>
Output:
int main( ) Number=3
{ Character=a
Real number=34.45
int num=3; String=hello
cout << “number=”<<num<<”\n”;
char ch=’a’;
cout << “character=”<<ch<<”\n”;
float fa=-34.45;
cout<<”real number=”<<fa<<”\n”;
string name= “hello”;
cout<<”string=”<<name<<”\n”;
return 0;
}
Defining Constants

 There are two simple ways in C++ to define constants

 Using #define preprocessor.

 Using const keyword

The #define Preprocessor

 Following is the form to use #defines preprocessor to define a constant

#define identifier value


Following example explains it in detail

#include <iostream.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0; 50
}

When the above code is compiled and executed, it


produces the following result
The const Keyword

You can use const prefix to declare constants with a


specific type as follows
const type variable = value;

Following example explains it in detail:


#include <iostream.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH; Output
cout << area; 50
cout << NEWLINE;
return 0;
}
Operators
 An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.

 Operators are symbols that perform operations on variables and values

 C++ is rich in built-in operators and provide the following types of


operators
 Assignment Operators

 Arithmetic Operators

 Relational and equality operators

 Logical operators

 Conditional operator

 Bitwise Operators
Assignment Operators (=)

 The assignment operator assigns a value to a variable.

a = 5;

 This statement assigns the integer value 5 to the variable a

 The part at the left of the assignment operator (=) is known as the lvalue
(left value) and the right one as the rvalue (right value).

 The lvalue has to be a variable where as the rvalue can be either a


constant, a variable, the result of an operation or any combination of
these
Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

Operator Example Equivalent To


= 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
|= n |= 0xF2F2 n = n | 0xF2F2
^= n ^= 0xF2F2 n = n ^ 0xF2F2
<<= n <<= 4 n = n << 4
>>= n >>= 4 n = n >> 4
Arithmetic Operators

 C++ provides five basic arithmetic operators


Operator Name Example
+ Addition 12 + 4.9 // gives 16.9
- Subtraction 3.98 - 4 // gives -0.02
* Multiplication 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5
% Remainder 13 % 3 //gives 1
Arithmetic operators.

 Modulo is the operation that gives the remainder of a division of two values.
For example, if we write:
a = 11 % 3; 2
Increase and decrease (++, --)

 the increase operator (++) and the decrease operator (--) increase or
reduce by one the value stored in a variable c++;
c+=1;
c=c+1;
 They are equivalent to +=1 and to -=1, respectively

 Are all equivalent in its functionality: the three of them increase by one
the value of c

 A characteristic of this operator is that it can be used both as a prefix and


as a suffix
 That means that it can be written either before the variable identifier (++a) or after it (a+

+)

 a++ or ++a both have exactly the same meaning

 a prefix (++a) the value is increased before

 a suffix (a++) the value stored in a is increased after being evaluated

 In Example 1, B is increased before its value is copied to A. While in Example 2, the

value of B is copied to A and then B is increased


Relational and equality operators ( ==, !=, >, <, >=, <= )

In order to evaluate a comparison between two expressions


we can use the relational and equality operators

The result of a relational operation is a Boolean value that


can only be true or false
Logical operators ( !, &&, || )

 The Operator ! is the C++ operator to perform the Boolean operation NOT
 producing false if its operand is true and true if its operand is false

 && Operator
 The operator && corresponds with Boolean logical operation AND
 This operation results true if both its two operands are true, and false otherwise
a b A&&b
True True True
True False False
False True False
false False False
|| operator

 The operator || corresponds with Boolean logical operation OR

 This operation results true if either one of its two operands is true,

 Thus being false only when both operands are false themselves
a b a || b
True True True
True False True
False True True
false False False
Conditional operator ( ? )

 The conditional operator evaluates an expression returning a value if that expression is

true and a different one if the expression is evaluated as false

 Its format is:


 condition ? result1 : result2

 If condition is true the expression will return result1, if it is not it will return result2

Example:-

7 == 5 ? 4:3 //returns 3, since 7 is not equal to 5.

7 == 5+2 ? 4:3 //returns 4, since 7 is equal to 5+2.


// conditional operator
#include <iostream>
using namespace std;
int main ()
{
int a,b,c;
a=2; Output
7
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}
Bitwise Operators
 Bitwise AND (&) takes two numbers as operands and does AND on every bit of two numbers. The result of
AND is 1 only if both bits are 1.

 Bitwise OR ( | ) takes two numbers as operands and does OR on every bit of two numbers. The result of
OR is 1 if any of the two bits is 1.

 Bitwise XOR (^ ) takes two numbers as operands and does XOR on every bit of two numbers. The result
of XOR is 1 if the two bits are different.

 Left shift (<<) takes two operands, left shifts the bits of the first operand, the second operand decides the
number of places to shift.

 Right shift (>>) takes two operands, right shifts the bits of the first operand, the second operand decides
the number of places to shift.

 Bitwise NOT (~ ) takes one number and inverts all bits of it


#include <iostream>
int main()
{
unsigned int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)

cout<< "a&b = “ << a & b;


Output
cout<< "a|b = " << a | b;

cout<< "a^b = " << a ^ b; a&b = 1


a|b = 13
cout<< "~a = "<< a = ~a;
a^b = 12
cout<< "b<<1 = " << b << 1; ~a = 250
cout<< "b>>1 = " << b >> 1; b<<1 = 18
return 0;
b>>1 = 4
}
Precedence of operators

When writing complex expressions with several


operands,
 we may have some doubts about which operand is
evaluated first and which later
Example:-
a = 5+7 % 2
Precedence of operators
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right


Unary ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= Right to left
^= |=
Precedence of operators

Exercise: find the value of A based on precedence


rule.
a = 20 - 4 / 5 * 2 + 3 * 5 % 4
THE END

You might also like