UNIT 1
UNIT 1
UNIT 1
Programming Languages
• Programming languages are used to create programs that control the behavior of a system, to express
algorithms or as a mode of human communication.
• Programming languages have a vocabulary of keywords, syntax and semantics for instructing a
computer to perform specific tasks. Such languages include s BASIC, C, C++, COBOL, FORTRAN,
Ada, and Pascal to name a few.
• While programming languages are easy for the humans to read and understand, the computer
understands the machine language that consists of numbers only.
• In between these two languages, there is assembly language which is similar to machine languages, but
is much easier to program in because they allow a programmer to substitute names for numbers.
• The question of which language is best depends on the following factors:
• The type of computer on which the program has to be executed
• The type of program
• The expertise of the programmer
First Generation: Machine Language
• Machine (or low level) language was used to program the first stored-program computer systems. It is the only
language that the computer understands. All the commands and data values are expressed using 1s and 0s.
• In 1950s each computer had its own native language, and programmers had to combine numbers to represent
instructions such as add and subtract. Although there were similarities between each of the machine language but a
computer could not understand programs written in another machine language
• The main advantage of machine language is that the code can run very fast and efficiently, since it is directly
executed by the CPU.
• However, this language is difficult to learn and is far more difficult to edit if errors occur. Moreover, if new
instructions are to be added into memory at some location, then all the instructions after the insertion point would
have to be moved down to make room in memory to accommodate the new instruction.
• Also code written in machine language is not portable. ue to resolve.
First Generation: Machine Language (Contd..)
The following instructions are a part of assembly language code to illustrate addition of two numbers
Third Generation Programming Language
• It is a refinement of 2GL which spurred the great increase in data processing that occurred in the
1960s and 1970s. in these languages, the program statements are not closely related to the internal
characteristics of the computer and is therefore often referred to has high-level languages.
• Generally, a statement written in a high-level programming language will expand into several
machine language instructions.
• 3GLs made programming easier, efficient and less prone to errors. They fall somewhere between
natural languages and machine languages. 3GL includes languages like FORTRAN and COBOL.
• A translator is needed to translate the instructions written in high level language into computer-
executable machine language. Such translators are commonly known as interpreters and
compilers.
• 3GLs makes it easier to write and debug a program and gives the programmer more time to think
about its overall logic. The programs written in such languages are portable between machines.
Fourth Generation: Very High-Level Languages
• 4GLs are nonprocedural languages. When writing code using a procedural language, the
programmer has to tell the computer how a task is done. In striking contrast, while using a
nonprocedural language the programmers define only what they want the computer to do, without
supplying all the details of how it has to be done.
• 5GLs are centered on solving problems using constraints given to the program, rather
than using an algorithm written by a programmer. They are widely used in artificial
intelligence research. Typical examples of a 5GL include Prolog, OPS5, and Mercury.
• Another aspect of a 5GL is that it contains visual tools to help develop a program. A good
example of a fifth generation language is Visual Basic. 5GLs are designed to make the
computer solve a given problem without the programmer.
•
Algorithm
• “Algorithm" is a formally defined procedure for performing some calculation. If a procedure is
formally defined, then it must be implemented using a programming language.
• The algorithm gives logic of the program, that is, a step-by-step description of how to arrive at a
solution.
• Algorithm provides a blueprint to write a program to solve a particular problem in finite number of
steps.
• Algorithms are mainly used to achieve software re-use.
• In order to qualify as an algorithm, a sequence of instructions must process the following
characteristics:
• Instructions must be precise
• Instructions must be unambiguous
• Not even a single instruction must be repeated infinitely
• After the algorithm gets terminated, the desired result must be obtained
Key Features of an Algorithm
• Any algorithm has a finite number of steps and some steps may involve decision
making, repetition.
• Broadly speaking, an algorithm exhibits three key features that can be given as:
• Sequence: Sequence means that each step of the algorithm is executed in the specified
order.
• Decision: Decision statements are used when the outcome of the process depends on some
condition.
• Repetition: Repetition which involves executing one or more steps for a number of times
can be implemented using constructs like the while, do-while and for loops. These loops
executed one or more steps until some condition is true.
Algorithm to add two numbers
• Step 1: Input first number as A
• Step 2: Input second number as B
• Step 3: Set Sum = A + B
• Step 4: Print Sum
• Step 5: End
Flowchart
• A flow chart is a graphical or symbolic representation of a process. They are basically used to design
and document complex processes to help the viewers to visualize the logic of the process so that they
can gain a better understanding of the process and find flaws, bottlenecks, and other less-obvious
features within it.
• Start and end symbols also known as the terminal symbol is always the first and the last symbol in a
flowchart.
• Generic processing step also called an activity is represents instructions like add a to b, save the result.
• Input/ Output symbols are represented as a parallelogram and are used to get input from users or
display the results to them.
• A Conditional or decision symbol is used to depict a Yes/No question or True/False test.
• Labeled connectors represented by an identifying label inside a circle are used in complex or multi-
sheet diagrams to substitute for arrows.
Flowchart to add two numbers
Start
Calculate SUM = A + B
Print SUM
End
Advantages of Flowcharts
• A flowchart is a diagrammatic representation that illustrates the sequence of steps that must
be performed to solve a problem. They are usually drawn in the early stages of formulating
computer solutions to facilitate communication between programmers and business people.
• Flowcharts help programmers to understand the logic of complicated and lengthy problems.
• They help to analyze the problem in a more effective manner
• Flowchart is also used for program documentation. Flowchart can be used to debug
programs that have error(s).
Limitations of using Flowcharts
End
Introduction to C
• You can choose any name for the functions. Every program must contain Function2()
{
one function that has its name as main(). Statement 1;
Statement 2;
• All functions(Including main()) are divided into two parts- the declaration ……………
……………
section and the statement section. Statement N;
}
• The declaration section precedes the statement section and is used to ………………….
………………….
describe the data that will be used in the function. FunctionN()
• Data declared within function are known as local declaration as that data is {
Statement 1;
visible only within that function. Statement 2;
……………
• The statement section in a function contains the code that manipulates the ……………
Statement N;
data to perform a specified task. }
Writing the first C Program
#include<stdio.h>
int main()
{
printf("\n Welcome to the world of C ");
return 0;
}
• Output
Welcome to the world of C
Files Used in a C Program
Files in a C program
Header Files
● When working with large projects, it is often desirable to make sub-routines and store
them in a different file known as header file. The advantage of header files can be realized
when
a) The programmer wants to use the same subroutines in different programs.
b) The programmer wants to change, or add, subroutines, and have those changes be
reflected in all other programs.
● Conventionally, header files names ends with a “.h” extension and its name can use only
letters, digits, dashes, and underscores.
● While some standard header files are available in C, but the programmer may also create
his own user defined header files.
● Standard Header Files: string.h, stdlib.h, stdio.h, math.h, alloc.h, conio.h
Files Used in a C Program(Contd..)
Object Files
● Object files are generated by the compiler as a result of processing the source code
file.
● Object files contain compact binary code of the function definitions.
● Linker uses this object file to produce an executable file (.exe file) by combining
the of object files together.
● Object files have a “.o” extension, although some operating systems including
Windows and MS-DOS have a “.obj” extension for the object file.
Binary Executable File
● The binary executable file is generated by the linker.
● The linker links the various object files to produce a binary file that can be directly
executed.
● On Windows operating system, the executable files have “.exe” extension.
Compiling and Executing C Programs
• C is a compiled language. C program must run through a C compiler that can
create an executable file to be run by the computer.
• The programming process starts with creating a source file that consists of the
statements of the program written in C language.
• The source file is then processed by a special program called a Compiler.
• The Compiler translates the source code into an object code.
• The object code contains the machine instructions for the CPU, and calls to OS
API.
• In the next step, the object file is processed with another special program called a
linker.
• The output of the linker is an executable or runnable file.
Library
Files
Compiling and Executing C Programs(contd..)
Pre- Object Executable
Source Linke Files
File processor Compiler Files
r
Library Library
Files Files
• In modular programming, the source code is divided into two or more source files.
• All these source files are complied separately thereby producing multiple object
files.
• These object files are combined by the linker to produce an executable file as
shown in above figure.
Using Comments
● It is a good programming practice to place some comments in the code to help the
reader understand the code clearly.
● Comments are just a way of explaining what a program does. It is merely an
internal program documentation.
● The compiler ignores the comments when forming the object file. This means that
the comments are non-executable statements.
● C has a set of 32 reserved words often known as keywords. All keywords are
basically a sequence of characters that have a fixed meaning. By convention all
keywords must be written in lowercase (small) letters.
● Example:
auto, break, case, const, char, continue, default, double, do, else, enum, extern, float,
for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch,
typedef, union, unsigned, void, volatile, while
Identifiers
●Identifiers are names given to program elements such as variables, arrays and functions.
Rules for forming identifier name
●it cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc) except
the underscore"_".
●There cannot be two successive underscores
●Keywords cannot be used as identifiers
●The names are case sensitive. So, example, “FIRST” is different from “first” and “First”.
●It must begin with an alphabet or an underscore.
●It can be of any reasonable length. Though it should not contain more than 31 characters.
Example,
int emp_num;
float salary;
char grade;
unsigned short int acc_no;
Initializing Variables
• While declaring variables, we can also initialize with value.
• int emp_num=7;
• int count, flag=0;
• int count=0, flag=1;
• When variables are declared but not initialized they usually contain garbage values.
Constants
● Constants are identifiers whose value does not change.
● Constants are used to define fixed values like PI or the charge on an electron so that their value does not get changed in
the program even by mistake.
● The value of the constant is known to the compiler at the compile time.
● 4 constants types: int, float, char and string
● Integer constants:
● 1234-int, 1234567L or l-long int, 1234U or u-unsigned int
● Integer literals –expressed in decimal, octal or hexadecimal
● Embedded spaces, commas, & non-digit chars not allowed in integer constants(123 456, 12,56,678, $123)
● -123-decimal, 012-octal(preceded by zero), 0x7F-hexadecimal(preceded with 0Xor0x)
● Floating point Constants:
● FP const-int part, decimal point, fractional part, & exponent field(E or e)
● Literal like 0.07 is by default treated as double.
● 0.02F- float type, 3.141592654L- long double, 0.5e2, -5.6E+3
● Character Constants: single char enclosed in single quotes- ‘a’
● String Constants: sequence of char enclosed in double quotes.
● “a” and ‘a’ is not same
● String chars are stored in successive memory locations.
● Compiler records the address of 1st char and appends a null char(‘\0’) to mark the end.
●
Constants
● To declare a constant, precede the normal variable declaration with const keyword and assign it
a value.
● For example, const float pi = 3.14;
● Another way to designate a constant is to use the pre-processor command define.
#define PI 3.14159
When the preprocessor reformats the program to be compiled by the compiler, it replaces each
defined name with its corresponding value wherever it is found in the source program. Hence, it
just works like the Find and Replace command available in a text editor.
• C language supports two kinds of equality operators to compare their operands for
strict equality or inequality.
• They are equal to (==) and not equal to (!=) operator.
• The equality operators have lower precedence than the relational operators.
OPERATOR MEANING
● As in case of arithmetic expressions, the logical expressions are evaluated from left to right.
Ex : (a<b) || (b>c)
● The bitwise AND operator (&) is a small version of the boolean AND (&&) as it performs operation on bits instead of
bytes, chars, integers, etc.
● The bitwise OR operator (|) is a small version of the boolean OR (||) as it performs operation on bits instead of bytes,
chars, integers, etc.
● The bitwise NOT (~), or complement, is a unary operation that performs logical negation on each bit of the operand.
By performing negation of each bit, it actually produces the ones' complement of the given binary value.
● The bitwise XOR operator (^) performs operation on individual bits of the operands. The result of XOR operation is
shown in the table A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
Bitwise Shift Operators
• C Supports two bitwise operators
• Shift-left (<<), Syntax : operand op num
• Shift-right (>>), Syntax : operand op num
• In bitwise shift operations, the digits are moved, or shifted, to the left or right.
• The CPU registers have a fixed number of available bits for storing numerals, so
when we perform shift operations; some bits will be "shifted out" of the register at
one end, while the same number of bits are "shifted in" from the other end.
• In a left arithmetic shift, zeros are shifted in on the right. For example;
unsigned int x = 11000101;
Then x << 2 = 00010100
• If a right arithmetic shift is performed on an unsigned integer then zeros are
shifted on the left. For example;
unsigned int x = 11000101;
Assignment Operators
• The assignment operator is responsible for assigning values to the variables.
• While the equal sign (=) is the fundamental assignment operator and has right to left
associativity
• C also supports other assignment operators that provide shorthand ways to represent
common variable assignments and the syntax is : variable op = expression
• They are shown in the table.
OPERATOR SYNTAX EQUIVALENT TO
/= variable /= expression variable = variable / expression
\= variable \= expression variable = variable \ expression
*= variable *= expression variable = variable * expression
+= variable += expression variable = variable + expression
-= variable -= expression variable = variable - expression
&= variable &= expression variable = variable & expression
^= variable ^= expression variable = variable ^ expression
<<= variable <<= amount variable = variable << amount
>>= variable >>= amount variable = variable >> amount
Comma Operator
● The comma operator in C takes two operands. It works by evaluating the first and
discarding its value, and then evaluates the second and returns the value as the
result of the expression.
● Comma separated operands when chained together are evaluated in left-to-right
sequence with the right-most value yielding the result of the expression.
● Among all the operators, the comma operator has the lowest precedence.
For example,
int a=2, b=3, x=0;
x = (++a, b+=a);
Now, the value of x = 6
Sizeof Operator
●sizeof is a unary operator used to calculate the sizes of data types.
●It can be applied to all data types.
●The operator returns the size of the variable, data type or expression in bytes.
●‘sizeof’ operator is used to determine the amount of memory space that the
variable/expression/data type will take.
For example,
●sizeof(char) returns 1, that is the size of a character data type. If we have,
int a = 10;
unsigned int result;
result = sizeof(a);
then result = 2,
Operator Precedence Chart
• C operators have two properties: Priority and Operator Assoc Operator Assoc
associativity.
(), [], . , -> L to R & L to R
• When an expression has more than 1 operator, then
it is the relative priorities of the operators wrt each ++, -- (postfix) R to L ^ L to R
other that determine the order in which the ++, --(prefix), +, -
expression will be evaluated. (unary), !, ~(type), R to L
| L to R
*(indirection),
• Associativity defines the direction in which the &(address), sizeof
operator acts on the operands. It can be Left to
Right / Right to Left. *, /, % L to R && L to R
It inserts some whitespace to the left of the cursor and moves the
\t Horizontal Tab
cursor accordingly.
●Type casting is also known as forced conversion. It is done when the value of a
higher data type has to be converted into the value of a lower data type.