0% found this document useful (0 votes)
11 views50 pages

FOP_Unit-1

The document provides an introduction to computer programming, covering computer languages, programming paradigms, and the programming process. It classifies computer languages into machine, assembly, and high-level languages, and discusses the characteristics and uses of each. Additionally, it outlines the programming development cycle, pseudocode, flowcharts, and the structure of a C++ program.

Uploaded by

shwerghu2003
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)
11 views50 pages

FOP_Unit-1

The document provides an introduction to computer programming, covering computer languages, programming paradigms, and the programming process. It classifies computer languages into machine, assembly, and high-level languages, and discusses the characteristics and uses of each. Additionally, it outlines the programming development cycle, pseudocode, flowcharts, and the structure of a C++ program.

Uploaded by

shwerghu2003
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/ 50

1

Unit-1:
Introduction to Computer Programming

Computer Languages:
• The computer language is defined as code or syntax which is used to
write programs or any specific applications.
• The computer language is used to communicate with computers.
• Broadly the computer language can be classified into three categories:
1. Assembly language
2. Machine language
3. High-level language.

Machine Language:
• The machine language is considered as oldest computer language
among all three.
• In machine language, the input is directly given as binary input which
is processed by the machine.
• It is considered a native language as it can be directly understood by a
central processing unit (CPU).
• The machine language is not so easy to understand.
• The operating system of the computer system is used to identify the
exact machine language used for that particular system.
• Example of machine language for the text “Hello World”.
01001000 0110101 01101100 01101100 01101111 00100000
01010111 01101111 01110010 01101100 01100100.

Assembly Language:
• The assembly language is considered a low-level language for
microprocessors and many programmable devices.
• The assembly language is also considered as second-generation
language.
• The assembly language is mostly famous for writing an operating
system and also in writing different desktop applications.
• The drawback of assembly language is the code cannot be reused and
the language is not so easy to understand.
2

• The operations performed using the assembly language is very fast.


The operations are much faster when it is compared to high-level
language.

High-Level Language:
• The high-level language is easy to understand and the code can be
written easily as the programs written are user-friendly in a high-level
language.
• The other advantage of code written in a high-level language is the
code is independent of a computer system.
• The high-level of language focus on programming language rather
than focusing on computer hardware components like register
utilization or memory utilization.
• The development of higher-level language is done for a programmer
to write a human-readable program that can be easily understood by
any user.
• The only requirement in a high-level language is the need of compiler.
• The examples of high-level language are C++, C, JAVA, FORTRAN,
Pascal, Perl, Ruby, and Visual Basic.
3

Programming paradigms:
• Programming paradigms are a way to classify programming
languages based on their features.
• Languages can be classified into multiple paradigms.
• Programming paradigm is an approach to solve problem using some
programming language or method to solve a problem using tools and
techniques that are available.

Common programming paradigms include:


• Imperative in which the programmer instructs the machine how to
change its state,
– Procedural which groups instructions into procedures,
– object-oriented which groups instructions with the part of the
state they operate on

• Declarative in which the programmer merely declares properties of


the desired result, but not how to compute it
– Functional in which the desired result is declared as the value of
a series of function applications,
– Logic in which the desired result is declared as the answer to a
question about a system of facts and rules,
– Mathematical in which the desired result is declared as the
solution of an optimization problem
– Reactive in which the desired result is declared with data
streams and the propagation of change

Imperative programming paradigm:


• It is one of the oldest programming paradigm. It features close relation
to machine architecture. It works by changing the program state
through assignment statements. It performs step by step task by
changing state.
• The main focus is on how to achieve the goal. The paradigm consist of
several statements and after execution of all the result is stored.
• Advantage:
- Very simple to implement
- It contains loops, variables etc.
4

• Disadvantage:
- Complex problem cannot be solved
- Less efficient and less productive
- Parallel programming is not possible
• Examples of Imperative programming paradigm:
C: developed by Dennis Ritchie and Ken Thompson
Fortan: developed by John Backus for IBM
Basic: developed by John G Kemeny and Thomas E Kurtz

Declarative programming paradigm:


• It is divided as Logic, Functional, Database.
• In computer science the declarative programming is a style of building
programs that expresses logic of computation without talking about
its control flow.
• It may simplify writing parallel programs.
• The focus is on what needs to be done rather how it should be done
basically emphasize on what code is actually doing.
• It just declares the result we want rather how it has be produced.
• This is the only difference between imperative (how to do) and
declarative (what to do) programming paradigms.
5

Programming Process:

Program development cycle:


Program development cycle can be divided into seven steps:
1. Understand the problem
2. Plan the logic
3. Code the program
4. Use software to translate the program into machine language
5. Test the program
6. Put the program into production
7. Maintain the program

➢ Understanding the Problem: To solve any problem programmer


first need to understand the problem.

➢ Planning the Logic:


• The heart of programming process lies in planning the
program’s logic.
• During this phase of the process, the programmer plans the
steps of program, deciding what steps to include and how to
order them.
• The two most common planning tools are flowcharts and
pseudo code.
6

➢ Coding the Program:


• After the logic is developed, only then can the programmer write
the program.
• As the programmer, next step is to code the program that is, to
express solution in a programming language.
• Programmer will translate the logic from the flowchart or
pseudo code or some other tool to a programming language.
• There are many programming languages: BASIC, COBOL, Pascal,
FORTRAN, C , C++ and Java are some examples.
➢ Translation:
• There are many programming languages, but computer knows
only machine language, which consists of 1s and 0s.
• Translator program is used to convert high-level programming
language to low-level machine language that computer
understand.
• Compiler: It is a translator which takes input i.e., High-Level
Language, and produces an output of low-level language i.e.
machine or assembly language. Its program run time is more
and occupies a larger part of memory. It has slow speed
because a compiler goes through the entire program and then
translates the entire program into machine codes.
• Interpreter: An interpreter is a program that translates a
programming language into a comprehensible language. –It
translates only one statement of the program at a time.
Interpreters, more often than not are smaller than compilers.
➢ Testing:
Once a program is free of syntax errors, the programmer can test
it- that is, execute it with some sample data to see whether the
results are logically correct.
➢ Putting program into production:
Once the program is tested adequately, it is ready for the
organization to use.
➢ Maintaining the program:
After programs are put into production, making necessary changes
is called maintenance.
7

Pseudocode Statements:
Pseudo code is a term which is often used in programming and algorithm-
based fields. It is a methodology that allows the programmer to represent
the implementation of an algorithm. Pseudo code, as the name suggests, is
a false code or a representation of code which can be understood by even a
layman with some school level programming knowledge.

Algorithm: It’s an organized logical sequence of the actions or the


approach towards a particular problem. A programmer implements an
algorithm to solve a problem. Algorithms are expressed using natural
verbal but somewhat technical annotations.

Pseudo code: It’s simply an implementation of an algorithm in the form of


annotations and informative text written in plain English. It has no syntax
like any of the programming language and thus can’t be compiled or
interpreted by the computer.

Advantages of Pseudocode:
• Improves the readability of any approach.
• It’s one of the best approaches to start implementation of an
algorithm.
• Acts as a bridge between the program and the algorithm or
flowchart.
• Also works as a rough documentation, so the program of one
developer can be understood easily when a pseudo code is written
out.
• The main goal of a pseudo code is to explain what exactly each line
of a program should do, hence making the code construction phase
easier for the programmer.

Some terms that used while writing pseudocode:


For starting: start/ begin
For End: stop/ end
For input: input/get/read/ accept
For output: output/ display/ print/ write
For calculation: set/calculate
8

Examples:
1. Write pseudocode to take input from user and print the value.
Start
Numeric myNumber
Input myNumber
Print myNumber
Stop

2. Write a pseudocode to find the sum of two numbers.


begin
numeric nNum1,nNum2,nSum
display "ENTER THE FIRST NUMBER : "
accept nNum1
display "ENTER THE SECOND NUMBER : "
accept nNum2
compute nSum=nNum1+nNum2
display "SUM OF THESE NUMBER : " nSum
end

3. Write a pseudocode to find the sum of three numbers.


begin
numeric nNum1,nNum2,nNum3,nSum
display "ENTER THE FIRST NUMBER : "
accept nNum1
display "ENTER THE SECOND NUMBER : "
accept nNum2
display "ENTER THE THIRD NUMBER : "
accept nNum3
nSum=nNum1+nNum2+nNum3
display "SUM OF ALL THREE NUMBERS : " nSum
end

4. Write a pseudocode to find the area of rectangle.


begin
numeric nLen,nBrd,nAre
display "ENTER THE LENGTH OF RECTANGLE : "
accept nLen
9

display "ENTER THE BREADTH OF RECTANGLE : "


accept nBrd
nAre=nLen*nBrd
display "AREA OF RECTANGLE : " nAre
end

5. Write a pseudocode to find the greatest of two numbers.


begin
numeric nNum1, nNum2
display "ENTER THE FIRST NUMBER : "
accept nNum1
display "ENTER THE SECOND NUMBER : "
accept nNum2
if(nNum1>nNum2)
begin
display "GREATEST ONE : " nNum1
end
else
begin
display "GREATEST ONE : " nNum2
end
end

6. Write a pseudocode to find the greatest of three numbers.


begin
numeric nNum1,nNum2,nNum3
display "ENTER THE FIRST NUMBER : "
accept nNum1
display "ENTER THE SECOND NUMBER : "
accept nNum2
display "ENTER THE THIRD NUMBER : "
accept nNum3
if(nNum1>nNum2)
begin
if(nNum1>nNum3)
begin
display "GREATEST ONE : " nNum1
10

end
else
begin
display "GREATEST ONE : " nNum3
end
end
else
begin
if(nNum2>nNum3)
begin
display "GREATEST ONE : " nNum2
end
else
begin
display "GREATEST ONE : " nNum3
end
end
end
11

Flowcharts:
Flowchart is a diagrammatic representation of sequence of logical steps of
a program. Flowcharts use simple geometric shapes to depict processes and
arrows to show relationships and process/data flow.

Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Symbol Symbol Name Purpose

Used at the beginning and end of the


Start/Stop algorithm to show start and end of the
program.

Indicates processes like mathematical


Process
operations.

Used for denoting program inputs and


Input/ Output
outputs.

Stands for decision statements in a


Decision program, where answer is usually Yes or No.

Shows relationships between different


Arrow shapes.

Connects two or more parts of a flowchart,


On-page Connector which are on the same page.

Connects two parts of a flowchart which are


Off-page Connector spread over different pages.
12

Examples:
1. Draw the flowchart to find sum of two numbers.
13

2. Draw the flowchart to check given number is even or odd.

3. Draw the flowchart to print 1 to 10 numbers.


14

Structure of C++ Program


The C++ program is written using a specific template structure.
The structure of the program written in C++ language is as follows:

Documentation Section:
• This section comes first and is used to document the logic of the
program that the programmer is going to code.
• It can also be used to write for the purpose of the program.
• Whatever written in the documentation section is the comment and is
not compiled by the compiler.
• The Documentation Section is optional since the program can execute
without them.

Below is the snippet of the same:

/* This is a C++ program to find the factorial of a number


The basic requirement for writing this
program is to have knowledge of loops
To find the factorial of number
iterate over range from number to one
*/
15

Linking Section:
The linking section contains two parts:
1. Header Files:
• Generally, a program includes various programming elements like
built-in functions, classes, keywords, constants, operators, etc. that are
already defined in the standard C++ library.
• In order to use such predefined elements in a program, an appropriate
header must be included in the program.
• Standard headers are specified in a program through the preprocessor
directive #include. When the compiler processes the instruction
#include<iostream>, it includes the contents of the stream in the
program. This enables the programmer to use standard input, output,
and error facilities that are provided only through the standard
streams defined in <iostream>. These standard streams process data
as a stream of characters, that is, data is read and displayed in a
continuous flow. The standard streams defined in <iostream> are
listed here.
#include<iostream>

2. Namespaces:
• A namespace permits grouping of various entities like classes, objects,
functions, and various C++ tokens, etc. under a single name.
• Any user can create separate namespaces of its own and can use them
in any other program.
• In the below snippets, namespace std contains declarations for cout,
cin, endl, etc. statements.
▪ using namespace std;
• Namespaces can be accessed in multiple ways:
○ using namespace std;
○ using std :: cout;

Definition Section:
• It is used to declare some constants and assign them some value.
• In this section, anyone can define your own datatype using primitive
data types.
• The #define preprocessor directive creates symbolic constants.
#define is a compiler directive which tells the compiler whenever the
16

message is found replace it with replacement-text before the program


is compiled.
• typedef int K; this statement telling the compiler that whenever you
will encounter K replace it by int and as you have declared k as
datatype you cannot use it as an identifier.

Global Declaration Section:


• Here the variables and the class definitions which are going to be used
in the program are declared to make them global.
• The scope of the variable declared in this section lasts until the entire
program terminates.
• These variables are accessible within the user-defined functions also.

Function Declaration Section:


• It contains all the functions which our main functions need.
• Usually, this section contains the User-defined functions.
• This part of the program can be written after the main function but for
this, write the function prototype in this section for the function which
you are going to write code after the main function.

Main Function:
• The main function tells the compiler where to start the execution of
the program. The execution of the program starts with the main
function.
• All the statements that are to be executed are written in the main
function.
• The compiler executes all the instructions which are written in the
curly braces {} which encloses the body of the main function.
• Once all instructions from the main function are executed control
comes out of the main function and the program terminates and no
further execution occurs.
17

Structure of Java Program


Java is an object-oriented programming, platform-independent, and
secure programming language that makes it popular. Using the Java
programming language, we can develop a wide variety of applications.

A typical structure of a Java program contains the following elements:


• Documentation Section
• Package Declaration
• Import Statements
• Interface Section
• Class Definition
• Class Variables and Variables
• Main Method Class
• Methods and Behaviors
18

Documentation Section
– The documentation section is an important section but optional for a
Java program.
– It includes basic information about a Java program. The information
includes the author's name, date of creation, version, program
name, company name, and description of the program.
– It improves the readability of the program. Whatever we write in the
documentation section, the Java compiler ignores the statements
during the execution of the program.
– To write the statements in the documentation section, we use
comments.
– The comments may be single-line, multi-line, and documentation
comments.
• Single-line Comment: It starts with a pair of forwarding slash (//).
For example:
//First Java Program
• Multi-line Comment: It starts with a /* and ends with */. We write
between these two symbols.
For example:
/*It is an example of
multiline comment*/
• Documentation Comment: It starts with the delimiter (/**) and
ends with */.
For example:
/**It is an example of documentation comment*/

Package Declaration
– The package declaration is optional.
– It is placed just after the documentation section. In this section, we
declare the package name in which the class is placed.
– Note that there can be only one package statement in a Java program.
– It must be defined before any class and interface declaration.
– It is necessary because a Java class can be placed in different packages
and directories based on the module they are used. For all these
classes the package belongs to a single parent directory.
– We use the keyword package to declare the package name.
19

For example:
1. package javatpoint; //where javatpoint is the package name
2. package com.javatpoint; //where com is the root directory and
javatpoint is the subdirectory

Import Statements
– The package contains the many predefined classes and interfaces.
– If we want to use any class of a particular package, we need to import
that class. The import statement represents the class stored in the
other package.
– We use the import keyword to import the class. It is written before
the class declaration and after the package statement.
– We use the import statement in two ways, either import a specific class
or import all classes of a particular package.
– In a Java program, we can use multiple import statements.
For example:
import java.util.Scanner; //it imports the Scanner class only
import java.util.*; //it imports all class of the java.util package

Interface Section
– It is an optional section.
– We can create an interface in this section if required. We use the
interface keyword to create an interface.
– An interface is slightly different from the class. It contains only
constants and method declarations. Another difference is that it
cannot be instantiated.
– We can use interface in classes by using the implements keyword.
For example:
interface car
{
void start();
void stop();
}

Class Definition
– In this section, we define the class. It is a vital part of a Java program.
– Without the class, we cannot create any Java program. A Java program
may contain more than one class definition.
20

– We use the class keyword to define the class.


– The class is a blueprint of a Java program. It contains information
about user-defined methods, variables, and constants.
– Every Java program has at least one class that contains the main()
method.
For example:
class Student //class definition
{

}
Class Variables and Constants
• In this section, we define variables and constants that are to be
used later in the program.
• In a Java program, the variables and constants are defined just
after the class definition.
• The variables and constants store values of the parameters. It is
used during the execution of the program.
For example:
class Student //class definition
{
String sname; //variable
int id;
double percentage;
}

Main Method Class


In this section, we define the main() method. It is essential for all Java
programs. Because the execution of all Java programs starts from the main()
method. In other words, it is an entry point of the class. It must be inside the
class. Inside the main method, we create objects and call the methods. We
use the following statement to define the main() method:
public static void main(String args[])
{

}
21

Data types
Data types specify the different sizes and values that can be stored in the
variable. All variables use data-type during declaration to restrict the type of
data to be stored.
Whenever a variable is defined in C++, the compiler allocates some memory
for that variable based on the data-type with which it is declared. Every data
type requires a different amount of memory.

C++:

Data types in C++ is mainly divided into three types:


1. Primitive Data Types
2. Derived Data Types
3. User-defined Data Types
22

1. Primitive data types:


These data types are built-in or predefined data types and can be used
directly by the user to declare variables.
Primitive data types available in C++ are:
○ Integer
○ Character
○ Boolean
○ Floating Point
○ Double Floating Point
○ Valueless or Void
○ Wide Character

Primitive data types available in C++.


• Integer: Keyword used for integer data types is int. Integers typically
requires 4 bytes of memory space and ranges from -2147483648 to
2147483647.
• Character: Character data type is used for storing characters.
Keyword used for character data type is char. Characters typically
requires 1 byte of memory space and ranges from -128 to 127 or 0 to
255.
• Boolean: Boolean data type is used for storing boolean or logical
values. A boolean variable can store either true or false. Keyword used
for boolean data type is bool.
• Floating Point: Floating Point data type is used for storing single
precision floating point values or decimal values. Keyword used for
floating point data type is float. Float variables typically requires 4
byte of memory space.
• Double Floating Point: Double Floating Point data type is used for
storing double precision floating point values or decimal values.
Keyword used for double floating point data type is double. Double
variables typically require 8 byte of memory space.
• void: Void means without any value. void datatype represents a
valueless entity. Void data type is used for those function which does
not returns a value.
• Wide Character: Wide character data type is also a character data
type but this data type has size greater than the normal 8-bit datatype.
Represented by wchar_t. It is generally 2 or 4 bytes long.
23

2. Derived Data Types:


The data-types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types.
These can be of four types namely:
○ Function
○ Array
○ Pointer
○ Reference
3. Abstract or User-Defined Data Types:
These data types are defined by the user itself. Like, defining a class in
C++ or a structure.
C++ provides the following user-defined datatypes:
○ Class
○ Structure
○ Union
○ Enumeration
○ Typedef defined Datatype

Data type Modifiers


As the name implies, data type modifiers are used with the built-in data types
to modify the length of data that a particular data type can hold.

Data type modifiers available in C++ are:


• Signed
• Unsigned
• Short
• Long
24

Below table summarizes the modified size and range of built-in datatypes
when combined with the type modifiers:
Data Type Size Range
(in bytes)

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

unsigned int 4 0 to 4,294,967,295

int 4 -2,147,483,648 to 2,147,483,647

long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

long long int 8 -(2^63) to (2^63)-1

unsigned long long int 8 0 to 18,446,744,073,709,551,615

signed char 1 -128 to 127

unsigned char 1 0 to 255

float 4

double 8

long double 12

wchar_t 2 or 4 1 wide character


25

Java:
There are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include
Classes, Interfaces, and Arrays

Java Primitive Data Types:


In Java language, primitive data types are the building blocks of data
manipulation.
There are 8 types of primitive data types:
• boolean data type
• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type
26

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type:


– The Boolean data type is used to store only two possible values: true
and false.
– This data type is used for simple flags that track true/false conditions.
– The Boolean data type specifies one bit of information, but its "size"
can't be defined precisely.
Example:
boolean one = false

Byte Data Type:


– The byte data type is an example of primitive data type. It's An 8-bit
signed two's complement integer.
– Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.
– The byte data type is used to save memory in large arrays where the
memory savings is most required.
– It saves space because a byte is 4 times smaller than an integer.
Example:
byte a = 10, byte b = -20
27

Short Data Type:


– The short data type is a 16-bit signed two's complement integer.
– Its value-range lies between -32,768 to 32,767 (inclusive). Its
minimum value is -32,768 and maximum value is 32,767.
– Its default value is 0.
– The short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.
Example:
short s = 10000, short r = -5000

Int Data Type:


– The int data type is a 32-bit signed two's complement integer.
– Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647
(2^31 -1) (inclusive). Its minimum value is - 2,147,483,648 and
maximum value is 2,147,483,647.
– Its default value is 0.
– The int data type is generally used as a default data type for integral
values unless there is no problem about memory.
Example:
int a = 100000, int b = -200000

Long Data Type:


– The long data type is a 64-bit two's complement integer.
– Its value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1). Its minimum value is -
9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807.
– Its default value is 0.
– The long data type is used when you need a range of values more than
those provided by int.
Example:
long a = 100000L, long b = -200000L

Float Data Type:


– The float data type is a single-precision 32-bit IEEE 754 floating point.
– Its value range is unlimited. It is recommended to use a float (instead
of double) if you need to save memory in large arrays of floating point
numbers.
28

– The float data type should never be used for precise values, such as
currency.
– Its default value is 0.0F.
Example:
float f1 = 234.5f

Double Data Type:


– The double data type is a double-precision 64-bit IEEE 754 floating
point.
– Its value range is unlimited.
– The double data type is generally used for decimal values just like float.
The double data type also should never be used for precise values,
such as currency.
– Its default value is 0.0d.
Example:
double d1 = 12.3

Char Data Type:


– The char data type is a single 16-bit Unicode character.
– Its value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535
inclusive).
– The char data type is used to store characters.
Example:
char letterA = 'A'
29

Variables:
A variable is a container which holds the value while the program is
executed. A variable is assigned with a data type.
Variable is a name of memory location. A variable is the name of a reserved
area allocated in memory. It is a combination of "vary + able" which means
its value can be changed.

Declaration of variables:
In order to use a variable in C++, we must first declare it specifying which of
the data types above we want it to be.
Syntax:
type variableName = value;
Where type is one of C++ types (such as int), and variableName is the name
of the variable (such as x or myName). The equal sign is used to assign values
to the variable.

For example:
int a;
float mynumber;
are valid declarations of variables.
The first one declares a variable of type int with the identifier a. The second
one declares a variable of type float with the identifier mynumber. Once
declared, variables a and mynumber can be used within the rest of their
scope in the program.

If you need to declare several variables of the same type and you want to save
some writing work you can declare all of them in the same line separating the
identifiers with commas.
For example:
int a, b, c;
declares three variables (a, b and c) of type int , and has exactly the same
meaning as if we had written:
int a;
int b;
int c;

Integer data types (char, short, long and int) can be signed or unsigned
according to the range of numbers that we need to represent. Thus to specify
30

an integer data type we do it by putting the keyword signed or unsigned


before the data type itself.
For example:
unsigned short NumberOfSons;
signed int MyAccountBalance;

By default, if we do not specify signed or unsigned it will be assumed that


the type is signed, therefore in the second declaration we could have
written:
int MyAccountBalance;

Initialization of variables:
When declaring a local variable, its value is undetermined by default. But you
may want a variable to store a concrete value the moment that it is declared.
In order to do that, you have to append an equal sign followed by the value
wanted to the variable declaration:
Syntax:
type identifier = initial_value ;
For example, if we want to declare an int variable called a that contains the
value 0 at the moment in which it is declared, we could write:
int a = 0;

Additionally, to this way of initializing variables, C++ has added a new way
to initialize a variable: by enclosing the initial value between parenthesis ():
type identifier (initial_value) ;
For example:
int a (0);
Both ways are valid and equivalent in C++.

For Example:
// operating with variables
#include <iostream.h>
int main ()
{
// declaring variables:
int a, b;
int result;
31

// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}

Scope of variables:
– All the variables that we are going to use must have been previously
declared. An important difference between the C and C++ languages is
that in C++ we can declare variables anywhere in the source code, even
between two executable sentences, and not only at the beginning of a
block of instructions, like happens in C.
– Global variables can be referred to anywhere in the code, within any
function, whenever it is after its declaration.
– The scope of the local variables is limited to the code level in which
they are declared. If they are declared at the beginning of a function
(like in main) their scope is the whole main function.
– If another function existed in addition to main(), the local variables
declared in main could not be used in the other function and vice
versa.
– In C++, the scope of a local variable is given by the block in which it is
declared (a block is a group of instructions grouped together within
curly brackets {} signs). If it is declared within a function, it will be a
variable with function scope, if it is declared in a loop its scope will be
only the loop, etc...
32

Identifiers:
– A valid identifier is a sequence of one or more letters, digits or
underline symbols (_).
– The length of an identifier is not limited, although for some compilers
only the 32 first characters of an identifier are significant (the rest are
not considered).
– Neither spaces nor marked letters can be part of an identifier. Only
letters, digits and underline characters are valid.
– In addition, variable identifiers should always begin with a letter.
– They can also begin with an underline character (_), but this is usually
reserved for external links. They can never begin with a digit.
– Another rule that you have to consider when inventing your
own identifiers is that they cannot match any key word of the C++
language.
– For example, the following expressions are always considered key
words according to the ANSI-C++ standard and therefore they must
not be used as identifiers:
asm, auto, bool, break, case, catch, char, class, const, const_cast,
continue, default, delete, do, double, dynamic_cast, else, enum,
explicit, extern, false, float, for, friend, goto, if, inline, int, long,
mutable, namespace, new, operator, private, protected, public,
register, reinterpret_cast, return, short, signed, sizeof, static,
static_cast, struct, switch, template, this, throw, true, try, typedef,
typeid, typename, union, unsigned, using, virtual, void, volatile,
wchar_t

Very important: The C++ language is "case sensitive", that means that an
identifier written in capital letters is not equivalent to another one with the
same name but written in small letters. Thus, for example the
variable RESULT is not the same as the variable result nor the
variable Result.
33

Constants:
Literals
A constant is any expression that has a fixed value. They can be divided in
Integer Numbers, Floating-Point Numbers, Characters and Strings.

Integer Numbers
1776
707
-273
they are numerical constants that identify integer decimal numbers. Notice
that to express a numerical constant we do not need to write quotes (") nor
any special character.

In addition to decimal numbers C++ allows the use as literal constants of


octal numbers (base 8) and hexadecimal numbers (base 16). If we want to
express an octal number, we must precede it with a 0 character (zero
character). And to express a hexadecimal number we have to precede it with
the characters 0x (zero, x).
For example, the following literal constants are all equivalent to each other:
75 // decimal
0113 // octal
0x4b // hexadecimal
All of them represent the same number: 75 (seventy five) expressed as a
radix-10 number, octal and hexadecimal, respectively.

Floating Point Numbers:


They express numbers with decimals and/or exponents. They can include a
decimal point, an e character (that expresses "by ten at the Xth height",
where X is the following integer value) or both.
3.14159 // 3.14159
6.02e23 // 6.02 x 1023
1.6e-19 // 1.6 x 10-19
3.0 // 3.0
these are four valid numbers with decimals expressed in C++.
34

Characters and strings:


There also exist non-numerical constants, like:
'z'
'p'
"Hello world"
"How do you do?"
The first two expressions represent single characters, and the following two
represent strings of several characters.
Notice that to represent a single character we enclose it between single
quotes (') and to express a string of more than one character we enclose
them between double quotes (").
When writing both single characters and strings of characters in a constant
way, it is necessary to put the quotation marks to distinguish them from
possible variable identifiers or reserved words.
Notice this:
x
'x'
x refers to variable x, whereas 'x' refers to the character constant 'x'.
35

Escape sequence:
Character constants and string constants have certain peculiarities, like
the escape codes. These are special characters that cannot be expressed
otherwise in the source code of a program, like newline (\n) or tab (\t). All
of them are preceded by an inverted slash (\). Here you have a list of such
escape codes:
\n newline
\r carriage return
\t tabulation
\v vertical tabulation
\b backspace
\f page feed
\a alert (beep)
\' single quotes (')
\" double quotes (")
\? question (?)
\\ inverted slash (\)

For example:
'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree"

constants of string of characters can be extended by more than a single code


line if each code line ends with an inverted slash (\):
"string expressed in \
two lines"
You can also concatenate several string constants separating them by one or
several blank spaces, tabulators, newline or any other valid blank character:
"We form" "a single" "string" "of characters"
36

Defined constants (#define):


You can define your own names for constants that you use quite often
without having to resort to variables, simply by using
the #define preprocessor directive. This is its format:
#define identifier value
For example:
#define PI 3.14159265
#define NEWLINE '\n'
#define WIDTH 100
they define three new constants. Once they are declared, you are able to use
them in the rest of the code as any if they were any other constant, for
example:
circle = 2 * PI * r;
cout << NEWLINE;
In fact the only thing that the compiler does when it finds #define directives
is to replace literally any occurrence of the them by the code to which they
have been defined.

For this reason, #define constants are considered macro constants.


The #define directive is not a code instruction, it is a directive for the
preprocessor, therefore it assumes the whole line as the directive and does
not require a semicolon (;) at the end of it.

Declared constants (const)


With the const prefix you can declare constants with a specific type exactly
as you would do with a variable:
const int width = 100;
const char tab = '\t';
const zip = 12440;
37

Operators:
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations.
The following are types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Conditional Operators

Arithmetic Operators:
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then
Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after B % A will give 0


an integer division

++ Increment operator, increases integer A++ will give 11


value by one

-- Decrement operator, decreases integer A-- will give 9


value by one
38

Increment and Decrement:


Another example of saving language when writing code are
the increase operator (++) and the decrease operator (--). They increase or
reduce by 1 the value stored in a variable.
They are equivalent to +=1 and to -=1, respectively.
Thus:
a++;
a+=1;
a=a+1;
are all equivalent in its functionality: the three increases by 1 the value of a.
A characteristic of this operator is that it can be used both as a prefix or as
a suffix. That means it can be written before the variable identifier (++a) or
after (a++).
Although in simple expressions like a++ or ++a they have exactly the same
meaning, in other operations in which the result of
the increase or decrease operation is evaluated as another expression they
may have an important difference in their meaning:
In case that the increase operator is used as a prefix (++a) the value is
increased before the expression is evaluated and therefore the increased
value is considered in the expression; in case that it is used as a suffix (a++)
the value stored in a is increased after being evaluated and therefore the
value stored before the increase operation is evaluated in the expression.
Notice the difference:
Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A is 4, B is 4 // A is 3, B is 4
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 B is later increased.
39

Assignment Operators:
A feature of assignation in C++ that contributes to its fame of sparing
language when writing are the compound assignation operators (+=, -
=, *= and /= among others), which allow to modify the value of a variable
with one of the basic operators:

There are following assignment operators supported by C++ language −

Operator Description Example

= Simple assignment operator, assigns


C = A + B will assign value of A
values from right side operands to
+ B into C
left side operand.

+= Add AND assignment operator, It


adds right operand to the left
C += A is equivalent to C = C + A
operand and assign the result to left
operand.

-= Subtract AND assignment operator,


it subtracts right operand from the
C -= A is equivalent to C = C - A
left operand and assign the result to
left operand.

*= Multiply AND assignment operator,


it multiplies right operand with the
C *= A is equivalent to C = C * A
left operand and assign the result to
left operand.

/= Divide AND assignment operator, it


divides left operand with the right
C /= A is equivalent to C = C / A
operand and assign the result to left
operand.

%= Modulus AND assignment operator,


C %= A is equivalent to C = C %
it takes modulus using two operands
A
and assign the result to left operand.
40

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment


C >>= 2 is same as C = C >> 2
operator.

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and


C ^= 2 is same as C = C ^ 2
assignment operator.

|= Bitwise inclusive OR and


C |= 2 is same as C = C | 2
assignment operator.

For example,
value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a - 5;
a /= b; is equivalent to a = a / b;
price *= units + 1; is equivalent to price = price * (units + 1);
and the same for all other operations.
41

Relational Operators:
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then –

Operator Description Example

== Checks if the values of two operands are equal (A == B) is not true.


or not, if yes then condition becomes true.

!= Checks if the values of two operands are equal (A != B) is true.


or not, if values are not equal then condition
becomes true.

> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.

< Checks if the value of left operand is less than (A < B) is true.
the value of right operand, if yes then condition
becomes true.

>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if
yes then condition becomes true.

<= Checks if the value of left operand is less than (A <= B) is true.
or equal to the value of right operand, if yes
then condition becomes true.

Here you have some examples:


(7 == 5) would return false.
(5 > 4) would return true.
(3 != 2) would return true.
(6 >= 6) would return true.
(5 < 5) would return false.
of course, instead of using only numeric constants, we can use any valid
expression, including variables. Suppose that a=2, b=3 and c=6,
(a == 5) would return false.
42

Logical Operators:
There are following logical operators supported by C++ language.
Logic operators && and || are used when evaluating two expressions to
obtain a single result. They correspond with boolean logic
operations AND and OR respectively. The result of them depends on the
relation between its two operands:
First Second
result result
Operand Operand
a && b a || b
a b
true true true true
true false false true
false true false true
false false false false

Assume variable A holds true and variable B holds false, then −

Operator Description Example

&& Called Logical AND operator. If both the operands (A && B) is false.
are non-zero, then condition becomes true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


operands is non-zero, then condition becomes
true.

! Called Logical NOT Operator. Use to reverses the !(A && B) is true.
logical state of its operand. If a condition is true,
then Logical NOT operator will make false.

For example:
((5 == 5) && (3 > 6) ) returns false ( true && false )
((5 == 5) || (3 > 6)) returns true ( true || false ).
43

Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows −
p Q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following
table.
Assume variable A holds 60 and variable B holds 13, then −

Operator Description Example

& Binary AND Operator copies a bit


(A & B) will give 12 which is 0000
to the result if it exists in both
1100
operands.

| Binary OR Operator copies a bit if (A | B) will give 61 which is 0011


it exists in either operand. 1101

^ Binary XOR Operator copies the


(A ^ B) will give 49 which is 0011
bit if it is set in one operand but
0001
not both.
44

~ Binary Ones Complement (~A ) will give -61 which is 1100


Operator is unary and has the 0011 in 2's complement form
effect of 'flipping' bits. due to a signed binary number.

<< Binary Left Shift Operator. The left


operands value is moved left by A << 2 will give 240 which is
the number of bits specified by the 1111 0000
right operand.

>> Binary Right Shift Operator. The


left operands value is moved right A >> 2 will give 15 which is 0000
by the number of bits specified by 1111
the right operand.

Conditional operator ( ? ):
The conditional operator evaluates an expression and returns a different
value according to the evaluated expression, depending on whether it
is true or false. Its format is:
condition ? result1 : result2
if condition is true the expression will return result1, if not it will
return result2.
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.
5>3 ? a : b returns a, since 5 is greater than 3.
a>b ? a : b returns the greater one, a or b.
45

Operator precedence:
Operator precedence determines the grouping of terms in an expression.
The associativity of an operator is a property that determines how operators
of the same precedence are grouped in the absence of parentheses. This
affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher
precedence than the addition operator:
For example, x = 7 + 3 * 2;
here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
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
Comma , Left to right
46

Type casting/ Type conversion:


A type cast is basically a conversion from one type to another. Typecasting
can be done in two ways: automatically by the compiler and manually by the
programmer or user. Type Casting is also known as Type Conversion.
There are two types of type conversion:
o Implicit Type Conversion:
- It is known as the automatic type casting.
- It automatically converted from one data type to another
without any programmer or user. It means the compiler
automatically converts one data type to another.
- All data type is automatically upgraded to the largest type
without losing any information.
- It can only apply in a program if both variables are compatible
with each other.
- It is possible for implicit conversions to lose information, signs
can be lost (when signed is implicitly converted to unsigned),
and overflow can occur (when long long is implicitly converted
to float).

char - sort int -> int -> unsigned int -> long int -> float -> double -
> long double, etc.

o Explicit Type Conversion:


- It is also known as the manual type casting in a program.
- It is manually cast by the programmer or user to change from
one data type to another type in a program. It means a user can
easily cast one data to another according to the requirement in
a program.
- It does not require checking the compatibility of the variables.
- In this casting, we can upgrade or downgrade the data type of
one variable to another in a program.
Syntax:
(type) expression;
type: It represents the user-defined data that converts the given
expression.
expression: It represents the constant value, variable, or an
expression whose data type is converted.
47

Input/Output: Streams and Formatting I/O:


C++ helps you to format the I/O operations like determining the number of
digits to be displayed after the decimal point, specifying number base etc.
The console is the basic interface of computers, normally it is the set
composed of the keyboard and the screen. The keyboard is generally the
standard input device and the screen the standard output device.

In the iostream C++ library, standard input and output operations for a
program are supported by two data streams:
cin for input and
cout for output.
Additionally, cerr and clog have also been implemented - these are two
output streams specially designed to show error messages. They can be
redirected to the standard output or to a log file.

Therefore cout (the standard output stream) is normally directed to the


screen and cin (the standard input stream) is normally assigned to the
keyboard.

Output (cout):
The cout stream is used in conjunction with the overloaded operator << (a
pair of "less than" signs).
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the content of variable x on screen

The << operator is known as insertion operator since it inserts the data that
follows it into the stream that precedes it. In the examples above it inserted
the constant string Output sentence, the numerical constant 120 and the
variable x into the output stream cout. Notice that the first of the two
sentences is enclosed between double quotes (") because it is a string of
characters. Whenever we want to use constant strings of characters, we
must enclose them between double quotes (") so that they can be clearly
distinguished from variables. For example, these two sentences are very
different:
cout << "Hello"; // prints Hello on screen
cout << Hello; // prints the content of Hello variable on screen
48

The insertion operator (<<) may be used more than once in a same sentence:
The utility of repeating the insertion operator (<<) is demonstrated when
we want to print out a combination of variables and constants or more than
one variable:
cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;

If we suppose that variable age contains the number 24 and the variable zip
code contains 90064 the output of the previous sentence would be:
Hello, I am 24 years old and my zipcode is 90064

It is important to notice that cout does not add a line break after its output
unless we explicitly indicate it, therefore, the following sentences:
cout << "This is a sentence.";
cout << "This is another sentence.";
will be shown followed in screen:
This is a sentence. This is another sentence.

even if we have written them in two different calls to cout. So, in order to
perform a line break on output we must explicitly order it by inserting a new-
line character, that in C++ can be written as \n:
Additionally, to add a new-line, you may also use the endl manipulator.
For example:
cout << "First sentence." << endl;
cout << "Second sentence." << endl;
would print out:
First sentence.
Second sentence.

The endl manipulator has a special behavior when it is used with buffered
streams: they are flushed. But anyway cout is unbuffered by default.
You may use either the \n escape character or the endl manipulator in order
to specify a line jump to cout.
49

Input (cin):
Handling the standard input in C++ is done by applying the overloaded
operator of extraction (>>) on the cin stream. This must be followed by the
variable that will store the data that is going to be read.
For example:
int age;
cin >> age;
declares the variable age as an int and then waits for an input
from cin (keyborad) in order to store it in this integer variable.

cin can only process the input from the keyboard once the RETURN key has
been pressed.
Therefore, even if you request a single character cin will not process the
input until the user presses RETURN once the character has been
introduced.
You must always consider the type of the variable that you are using as a
container with cin extraction. If you request an integer, you will get an
integer, if you request a character, you will get a character and if you request
a string of characters, you will get a string of characters.

// i/o example Please enter an integer


#include <iostream.h> value: 702
The value you entered is 702 and
int main () its double is 1404.
{
int i;
cout << "Please enter an integer
value: ";
cin >> i;
cout << "The value you entered is "
<< i;
cout << " and its double is " << i*2
<< ".\n";
return 0;
}
50

You can also use cin to request more than one datum input from the user:
cin >> a >> b;
is equivalent to:
cin >> a;
cin >> b;
In both cases the user must give two data, one for variable a and another for
variable b that may be separated by any valid blank separator: a space, a tab
character or a newline.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy