FOP_Unit-1
FOP_Unit-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
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.
• 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
Programming Process:
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.
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.
Examples:
1. Write pseudocode to take input from user and print the value.
Start
Numeric myNumber
Input myNumber
Print myNumber
Stop
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
Examples:
1. Draw the flowchart to find sum of two numbers.
13
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.
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
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
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
}
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;
}
}
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++:
Below table summarizes the modified size and range of built-in datatypes
when combined with the type modifiers:
Data Type Size Range
(in bytes)
float 4
double 8
long double 12
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
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
– 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
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
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.
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"
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
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:
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 –
> 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.
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
&& Called Logical AND operator. If both the operands (A && B) is false.
are 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 −
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
char - sort int -> int -> unsigned int -> long int -> float -> double -
> long double, etc.
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.
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.
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.