Principal of Programming Short Notes
Principal of Programming Short Notes
UNIT-1
Introduction
The concept of Programming Languages: Syntax, Semantics and pragmatics
There are 3 things that relate to the concept pemrogramanan language: syntax,
semantiks and pragmatic. 3 in teaching this concept uses the analogy of the ordinary
language we use everyday.
Syntax
The syntax of a language related to the structure of language. For example, to form a
valid sentence in the language we use the structure: [subject] + [verb] + [noun]. By
using this structure, we can form a sentence, for example: I eat rice. In connection with
the programming language, we must meet the syntax (read: the rules of language
structure) so that programs can run. For example, in the BASIC language, to
mengassign a variable with a value, we use the Operands '=', but if in Pascal, we
use':='. Example in BASIC: a = 1, but in the language Pascal, a: = 1.
Semantic
Semantics of a language describes the relationship between syntax and computational
models. Simply put, semantic explain the meaning of the program.
Following analogy. If we use the syntax [subject] + [verb] + [noun], we can produce
sentences.
If we generate the sentence I eat rice, so this sentence to meet the rules of syntax.
But, if I make a sentence I eat stones, the syntax of this sentence is correct. However,
semantically, this sentence does not contain significant meaning.
In connection with the programming language, sometimes there are times when a
programmer can not associate syntax computing model. Logic errors can easily occur.
if (a = 5) (
echo 'The value a = 5?;
)
If the program is run, what happens? Depending of what language is used. If the
language used is C, then the output comes out is always value a = 5, although a
previous variable value other than 5. Why did that happen? That's because the operator
'=' in C means mengassign a variable that is to the left with the existing value on the
right. In C, the syntax of this operation is correct.
But, if that meant the programmer wants to evaluate the value of a variable, then the
logic operators should wear'=='. Thus, the actual program to be
if (a == 5) (
echo 'The value a = 5?;
)
Pragmatic
Pragmatics associated with the ease of implementation and efficiency. In analogy with
the language, we can just tell the person "Do not smoke" when there are regulations
that prohibit a person smoking in a room. Such a short sentence is enough efficient.
But, in other occasions we might use the phrase "Please you do not smoke in here
because, according to government regulations in a number XXX XXX stated that
smoking in public places will lead to violations of regulations, other than that from the
health side ... blah blah blah".
The assignment token, =, should not be confused with equals, which uses the token ==. The
assignment statement binds a name, on the left-hand side of the operator, to a value, on the
right-hand side. This is why you will get an error if you enter:
>>> 17 = n
File "<interactive input>", line 1
SyntaxError: can't assign to literal
Tip
When reading or writing code, say to yourself “n is assigned 17” or “n gets the
value 17”. Don’t say “n equals 17”.
A common way to represent variables on paper is to write the name with an arrow pointing
to the variable’s value. This kind of figure is called a state snapshot because it shows what
state each of the variables is in at a particular instant in time. (Think of it as the variable’s
state of mind). This diagram shows the result of executing the assignment statements:
If you ask the interpreter to evaluate a variable, it will produce the value that is currently
linked to the variable:
>>> message
'What's up, Doc?'
>>> n
17
>>> pi
3.14159
We use variables in a program to “remember” things, perhaps the current score at the
football game. But variables are variable. This means they can change over time, just like the
scoreboard at a football game. You can assign a value to a variable, and later assign a
different value to the same variable. (This is different from maths. In maths, if you give `x`
the value 3, it cannot change to link to a different value half-way through your calculations!)
You’ll notice we changed the value of day three times, and on the third assignment we even
made it refer to a value that was of a different type.
A great deal of programming is about having the computer remember things, e.g. The
number of missed calls on your phone, and then arranging to update or change the variable
when you miss another call.
Statements
A statement is an instruction that the Python interpreter can execute. We have only seen the
assignment statement so far. Some other kinds of statements that we’ll see shortly
are while statements, for statements, if statements, and import statements. (There are
other kinds too!)
When you type a statement on the command line, Python executes it. Statements don’t
produce any result.
Expressions
An expression is a combination of values, variables, operators, and calls to functions. If you
type an expression at the Python prompt, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
>>> len("hello")
5
In this example len is a built-in Python function that returns the number of characters in a
string. We’ve previously seen the print and the type functions, so this is our third example
of a function!
The evaluation of an expression produces a value, which is why expressions can appear on
the right hand side of assignment statements. A value all by itself is a simple expression, and
so is a variable.
>>> 17
17
>>> y = 3.14
>>> x = len("hello")
>>> x
5
>>> y
3.14
1 int i, x = 0;
2 void main() {
3 for (i = 1; i <= 50; i++)
4 x += do_something(x);
5 }
Assignment
In computer programming, an assignment statement sets and/or re-sets the value stored in the
storage location(s) denoted by a variable name; in other words, it copies a value into the variable. In
most imperative programming languages, the assignment statement (or expression) is a
fundamental construct.
Today, the most commonly used notation for this basic operation has come to
be x = expr (originally Superplan 1949–51, popularized by Fortran 1957 and C) followed
by [1] x := expr (originally ALGOL 1958, popularised by Pascal),[2] although there are many other
notations in use. In some languages the symbol used is regarded as an operator (meaning that the
assignment statement as a whole returns a value) while others define the assignment as a
statement (meaning that it cannot be used in an expression).
Assignments typically allow a variable to hold different values at different times during its life-span
and scope. However, some languages (primarily strictly functional) do not allow that kind of
"destructive" reassignment, as it might imply changes of non-local state. The purpose is to
enforce referential transparency, i.e. functions that do not depend on the state of some variable(s),
but produce the same results for a given set of parametric inputs at any point in time. Modern
programs in other languages also often use similar strategies, although less strict, and only in certain
parts, in order to reduce complexity, normally in conjunction with complementing methodologies
such as data structuring, structured programming and object orientation.
l-values and r-values
L-value: “l-value” refers to memory location which identifies an object. l-value may
appear as either left hand or right hand side of an assignment operator(=). l-value often
represents as identifier.
Expressions referring to modifiable locations are called “modifiable l-values“. A
modifiable l-value cannot have an array type, an incomplete type, or a type with
the const attribute. For structures and unions to be modifiable lvalues, they must not
have any members with the const attribute. The name of the identifier denotes a
storage location, while the value of the variable is the value stored at that location.
An identifier is a modifiable lvalue if it refers to a memory location and if its type is
arithmetic, structure, union, or pointer. For example, if ptr is a pointer to a storage
region, then *ptr is a modifiable l-value that designates the storage region to
which ptr points.
In C, the concept was renamed as “locator value”, and referred to expressions that
locate (designate) objects. The l-value is one of the following:
1. The name of the variable of any type i.e, an identifier of integral, floating, pointer,
structure, or union type.
2. A subscript ([ ]) expression that does not evaluate to an array.
3. A unary-indirection (*) expression that does not refer to an array
4. An l-value expression in parentheses.
5. A const object (a nonmodifiable l-value).
6. The result of indirection through a pointer, provided that it isn’t a function pointer.
7. The result of member access through pointer(-> or .)
// a is an expression referring to an
// 'int' object as l-value
a = 1;
// Compilation error:
// as assignment is trying to change the
// value of assignment operator
R-value: r-value” refers to data value that is stored at some address in memory. A r-
value is an expression that can’t have a value assigned to it which means r-value can
appear on right but not on left hand side of an assignment operator(=).
p = &b;
struct S { int m; };
int x, y;
Similarly, you will need the following setup to start with programming using any
programming language.
Text Editor
A text editor is a software that is used to write computer programs. Your Windows
machine must have a Notepad, which can be used to type programs. You can launch it
by following these steps −
Start Icon → All Programs → Accessories → Notepad → Mouse Click on
Notepad
It will launch Notepad with the following window −
You can use this software to type your computer program and save it in a file at any
location. You can download and install other good editors like Notepad++, which is freely
available.
If you are a Mac user, then you will have TextEdit or you can install some other
commercial editor like BBEdit to start with.
Compiler?
You write your computer program using your favorite programming language and save
it in a text file called the program file.
Now let us try to get a little more detail on how the computer understands a program
written by you using a programming language. Actually, the computer cannot understand
your program directly given in the text format, so we need to convert this program in a
binary format, which can be understood by the computer.
The conversion from text program to binary file is done by another software called
Compiler and this process of conversion from text formatted program to binary format
file is called program compilation. Finally, you can execute binary file to perform the
programmed task.
We are not going into the details of a compiler and the different phases of compilation.
The following flow diagram gives an illustration of the process −
So, if you are going to write your program in any such language, which needs compilation
like C, C++, Java and Pascal, etc., then you will need to install their compilers before
you start programming.
Interpreter
We just discussed about compilers and the compilation process. Compilers are required
in case you are going to write your program in a programming language that needs to
be compiled into binary format before its execution.
There are other programming languages such as Python, PHP, and Perl, which do not
need any compilation into binary format, rather an interpreter can be used to read such
programs line by line and execute them directly without any further conversion.
So, if you are going to write your programs in PHP, Python, Perl, Ruby, etc., then you
will need to install their interpreters before you start programming.
Online Compilation
If you are not able to set up any editor, compiler, or interpreter on your machine,
then tutorialspoint.com provides a facility to compile and run almost all the programs
online with an ease of a single click.
So do not worry and let's proceed further to have a thrilling experience to become a
computer programmer in simple and easy steps.
Storage Allocation
In computer science, storage allocation is the assignment of particular areas of a
magnetic disk to particular data or instructions.
Example:
1. fact (int n)
2. {
3. if (n<=1)
4. return 1;
5. else
6. return (n * fact(n-1));
7. }
8. fact (6)
Constants
In computer programming, a constant is a value that cannot be altered by the program during
normal execution, i.e., the value is constant.[a] When associated with an identifier, a constant is said
to be "named," although the terms "constant" and "named constant" are often used interchangeably.
This is contrasted with a variable, which is an identifier with a value that can be changed during
normal execution, i.e., the value is variable. Constants are useful for both programmers and
compilers: For programmers they are a form of self-documenting code and allow reasoning
about correctness, while for compilers they allow compile-time and run-time checks that verify that
constancy assumptions are not violated, and allow or simplify some compiler optimizations.
There are various specific realizations of the general notion of a constant, with subtle distinctions
that are often overlooked. The most significant are: compile-time (statically-valued) constants, run-
time (dynamically-valued) constants, immutable objects, and constant types (const).
Typical examples of compile-time constants include mathematical constants, values from standards
(here maximum transmission unit), or internal configuration values (here characters per line), such
as these C examples:
Typical examples of run-time constants are values calculated based on inputs to a function, such as
this C++ example:
void f(std::string s) {
const size_t l = s.length();
// ...
}
constant initialization
Sets the initial values of the static variables to a compile-time constant.
Syntax
Explanation
Constant initialization is performed after (until C++14)instead of (since C++14) zero initialization of the static and
thread-local objects and before all other initialization. Only the following variables are constant initialized:
1) Static or thread-local references, if it is bound to static glvalue, to a temporary object (or its subobject), or to
a function, and if every expression (including implicit conversions) in the initializer of the reference is
a constant expression.
2) Static or thread-local object of class type that is initialized by a constructor call, if the constructor
is constexpr and all constructor arguments (including implicit conversions) are constant expressions, and if
the initializers in the constructor's initializer list and the brace-or-equal initializers of the class members only
contain constant expressions.
3) Static or thread-local object (not necessarily of class type), that is not initialized by a constructor call, if the
object is value-initialized or if every expression in its initializer is a constant expression.
The effects of constant initialization are the same as the effects of the corresponding initialization, except that
it's guaranteed that it is complete before any other initialization of a static or thread-local object begins, and it
may be performed at compile time.
Notes
The compiler is permitted to initialize other static and thread-local objects using constant initialization, if it can
guarantee that the value would be the same as if the standard order of initialization was followed.
In practice, constant initialization is performed at compile time, and pre-calculated object representations are
stored as part of the program image (e.g. in the .data section). If a variable is both const and constant-
initialized, its object representation may be stored in a read-only section of the program image (e.g.
the .rodata section)
Example
#include <iostream>
#include <array>
struct S {
static const int c;
};
const int d = 10 * S::c; // not a constant expression: S::c has no preceding
// initializer, this initialization happens after const
const int S::c = 5; // constant initialization, guaranteed to happen first
int main()
{
std::cout << "d = " << d << '\n';
std::array<int, S::c> a1; // OK: S::c is a constant expression
// std::array<int, d> a2; // error: d is not a constant expression
}
Output:
d = 50
Statement-level control structure