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

Module 1

Uploaded by

sanjibkumar2387
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Module 1

Uploaded by

sanjibkumar2387
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Computer

Programming
Languages
Computer Programming
Languages:
■ A programming language is an artificial language that
can be used to control the behavior of a machine,
particularly a computer

■ Programming languages, like human languages, are


defined through the use of syntactic and semantic rules,
to determine structure and meaning respectively.
Computer Programming
Languages (Contd…):

■ Programming languages are used to facilitate


communication about the task of organizing and
manipulating information, and to express algorithms
precisely.

■ For 50 years, computer programmers have been writing


code. New technologies continue to emerge, develop,
and mature at a rapid pace. Now there are more than
2,500 documented programming languages!
Non-computational
languages:
■ Non-computational languages, such as markup
languages like HTML or formal grammars like BNF, are
usually not considered programming languages.

■ Often a programming language is embedded in the


non-computational language.
Machine language:
• It is the lowest-level programming language.

• Machinelanguages are the only languages


understood by computers.
Machine language:

■ While easily understood by computers, machine


languages are almost impossible for humans to use
because they consist entirely of numbers.

For example, an x86/IA-32 processor can execute the


following binary instruction as expressed in machine
language:

Binary: 10110000 01100001 (Hexadecimal: 0xb061)


Assembly Level Language:

■ An assembly language is a low-level language for


programming computers.

■ The word "low" does not imply that the language is


inferior to high-level programming languages but rather
refers to the small or nonexistent amount of abstraction
between the language and machine language, because
of this, low-level languages are sometimes described as
being "close to the hardware."

■ It implements a symbolic representation of the numeric


machine codes and other constants needed to program
a particular CPU architecture.
Assembly Level
Language (contd…):
■ A utility program called an assembler, is used to translate assembly
language statements into the target computer's machine code.
■ The assembler performs a more or less isomorphic translation (a one-to-one
mapping) from mnemonic statements into machine instructions and data.
Example: Assembly language representation is easier to remember
(more mnemonic)

mov al, 061h

This instruction means:


Move the hexadecimal value 61 (97 decimal) into the processor register
named "al".

The mnemonic "mov" is an operation code or opcode, A comma-separated


list of arguments or parameters follows the opcode;
Example (Adds 2 numbers):

name "add"
mov al, 5 ; bin=00000101b
mov bl, 10 ; hex=0ah or bin=00001010b
add bl, al ; 5 + 10 = 15 (decimal) or hex=0fh or
bin=00001111b
High-level language:
■ High-level languages are relatively easy to learn
because the instructions bear a close resemblance to
everyday language, and because the programmer does
not require a detailed knowledge of the internal workings
of the computer.

■ Each instruction in a high-level language is equivalent to


several machine-code instructions, therefore it is more
compact than equivalent low-level programs.

■ High-level languages are used to solve problems and are


often described as problem-oriented languages
High-level language
(Contd…):
Examples of HLL:
■ BASIC was designed to be easily learnt by first-time
programmers;
■ COBOL is used to write programs solving business problems;
■ FORTRAN is used for programs solving scientific and
mathematical problems.
■ With the increasing popularity of windows-based systems, the
next generation of programming languages was designed to
facilitate the development of GUI interfaces;
for example, Visual Basic wraps the BASIC language in a
graphical programming environment.
■ Support for object-oriented programming has also become
more common, for example in C++ and Java.
Example (C program to add 2
numbers):
#include<stdio.h> //header files
void main()
{
int a, b, c; // declaration of 3 variables
printf(“Enter two numbers:\n”);
scanf(“%d”, &a); // read 1st number
scanf(“%d”, &b); // read 2nd number
c=a+b; // compute the sum
printf(“Sum of 2 numbers is %d”, c); //print sum
}
C Programming Language
■ C is a general-purpose programming language that is extremely popular,
simple, and flexible to use.
■ It is a structured programming language that is machine-independent and
extensively used to write various applications, Operating Systems like
Windows, and many other complex programs like Oracle database, Git,
Python interpreter, and more.
■ It is said that ‘C’ is a god’s programming language. One can say, C is a base
for the programming. If you know ‘C,’ you can easily grasp the knowledge
of the other programming languages that uses the concept of ‘C’
■ It is essential to have a background in computer memory mechanisms
because it is an important aspect when dealing with the C programming
language.
History
Features & Application

■ ‘C’ language is widely used in embedded systems.


■ It is used for developing system applications.
■ It is widely used for developing desktop applications.
■ Most of the applications by Adobe are developed using ‘C’ programming language.
■ It is used for developing browsers and their extensions. Google’s Chromium is built
using ‘C’ programming language.
■ It is used to develop databases. MySQL is the most popular database software
which is built using ‘C’.
■ It is used in developing an operating system. Operating systems such as Apple’s OS
X, Microsoft’s Windows, and Symbian are developed using ‘C’ language. It is used
for developing desktop as well as mobile phone’s operating system.
■ It is used for compiler production.
■ It is widely used in IOT applications.
Simple Program Logic
C Basic commands Explanation
#include <stdio.h> This command includes standard input output header
file(stdio.h) from the C library before compiling a C
program
int main() It is the main function from where C program execution
begins.
{ Indicates the beginning of the main function.
/*_some_comments_*/ Whatever written inside this command “/* */” inside a C
program, it will not be considered for compilation and
execution.
printf(“Hello_World! “); This command prints the output on the screen

getch(); This command is used for any character input from


keyboard.
return 0; This command is used to terminate a C program (main
function) and it returns 0.
} It is used to indicate the end of the main function.
Program Development Life Cycle
Flowchart
The Flowchart is the most widely used graphical representation of an algorithm and procedural
design workflows. It uses various symbols to show the operations and decisions to be followed in
a program. It flows in sequential order.

The various types of the flowchart are given below.

● Horizontal Flowchart
● Panoramic Flowchart
● Vertical Flowchart
● Architectural Flowchart
Rules & guidelines

● Only conventional flowchart symbols should be used.


● Proper use of names and variables in the flowchart.
● If the flowchart becomes large and complex, use
connector symbols.
● Flowcharts should have start and stop points.
The various symbols used in Flowchart Designs are given below.

Terminal Symbol: In the flowchart, it is represented with the help of a circle for denoting the start and stop symbol. The
symbol given below is used to represent the terminal symbol.

Input/output Symbol: The input symbol is used to represent the input data, and the output symbol is used to display the
output operation. The symbol given below is used for representing the Input/output symbol.
Processing Symbol:It is represented in a flowchart with the help of a rectangle box used to represent the
arithmetic and data movement instructions. The symbol given below is used to represent the processing
symbol.

Decision Symbol: Diamond symbol is used for represents decision-making statements. The symbol
given below is used to represent the decision symbol.
Connector Symbol:The connector symbol is used if flows discontinued at some point
and continued again at another place. The following symbol is the representation of the
connector symbol.

Flow lines: It represents the exact sequence in which instructions are executed. Arrows
are used to represent the flow lines in a flowchart. The symbol given below is used for
representing the flow lines

:
Hexagon symbol (Flat): It is used to create a preparation box containing the loop setting statement. The
symbol given below is used for representing the Hexagon symbol.

On-Page Reference Symbol: This symbol contains a letter inside that indicates the flow continues on a
matching symbol containing the same letters somewhere else on the same page. The symbol given below
is used for representing the on-page reference symbol.
Off-Page Reference: This symbol contains a letter inside indicating that the flow continues on a
matching symbol containing the same letter somewhere else on a different page. The symbol given below
is used to represent the off-page reference symbol.

Delay or Bottleneck: This symbol is used for identifying a delay in a flowchart. The alternative name
used for the delay is the bottleneck. The symbol given below is used to represent the delay or bottleneck
symbol.
Document Symbol: This symbol is used in a flowchart to indicate a document or report.The symbol
given below is used to represent the document symbol.

Internal storage symbol: The symbol given below is used to represent the internal storage symbol.
Advantages
Following are the various advantages of flowchart:

● Communication: A flowchart is a better way of communicating the logic of a program.


● Synthesis: Flowchart is used as working models in designing new programs and software systems.
● Efficient Coding: Flowcharts act as a guide for a programmer in writing the actual code in a high-level
language.
● Proper Debugging: Flowcharts help in the debugging process.
● Effective Analysis: Effective analysis of logical programs can be easily done with the help of a related
flowchart.
● Proper Documentation: Flowchart provides better and proper documentation. It consists of various
activities such as collecting, organizing, storing, and maintaining all related program records.
● Testing: A flowchart helps in the testing process.
● Efficient program maintenance: The maintenance of the program becomes easy with the help of a
flowchart.
Disadvantages
Following are the various disadvantages of flowchart:

● Time-consuming: Designing a flowchart is a very time-consuming process.


● Complex: It isn't easy to draw a flowchart for large and complex programs.
● There is no standard in the flowchart; there is no standard to determine the quantity of detail.
● Difficult to modify: It is very difficult to modify the existing flowchart.
Flowchart for finding the sum of first five natural numbers (
i.e. 1,2,3,4,5):
Flowchart (Example):
Flowchart to find the sum of first 50 natural numbers.
Flow Chart to find largest of two numbers:

Start

Read A, B

Yes Is A No
>B
Print
Print
B
A

End
Flowchart to find the largest of
three numbers A,B, and C:

NO
LIMITATIONS OF USING
FLOWCHARTS:
■ Complex logic: Sometimes, the program logic is quite
complicated. In that case, flowchart becomes complex
and clumsy.

■ Alterations and Modifications: If alterations are


required the flowchart may require re-drawing
completely.

■ Reproduction: As the flowchart symbols cannot be


typed, reproduction of flowchart becomes a problem.
Flowchart (Exercise):

1. Draw a flowchart to depict all steps that you do


reach your college.

2. Draw Flowchart for Linear search.


Programming & user enviornment

If you want to set up your environment for C programming language,


you need the following two software tools available on your computer,
(a) Text Editor and
(b) The C Compiler.
Text Editor
This will be used to type your program. Examples of few a editors include
Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For
example, Notepad will be used on Windows, and vim or vi can be used on
windows as well as on Linux or UNIX.
The files you create with your editor are called the source files and they contain
the program source codes. The source files for C programs are typically named
with the extension ".c".
Before starting your programming, make sure you have one text editor in place
and you have enough experience to write a computer program, save it in a file,
compile it and finally execute it.
Compiler
The source code written in source file is the human readable source for your
program. It needs to be "compiled", into machine language so that your CPU
can actually execute the program as per the instructions given.
The compiler compiles the source codes into final executable programs. The
most frequently used and free available compiler is the GNU C/C++ compiler,
otherwise you can have compilers either from HP or Solaris if you have the
respective operating systems.
The following section explains how to install GNU C/C++ compiler on
various OS. We keep mentioning C/C++ together because GNU gcc compiler
works for both C and C++ programming languages.
Hello World
A C program basically consists of the following parts −
● Preprocessor Commands
● Functions
● Variables
● Statements & Expressions
● Comments
Program

#include <stdio.h>

int main() {
/* my first program in C */
printf("Hello, World! \n");

return 0;
}
Explanation
● The first line of the program #include <stdio.h> is a preprocessor
command, which tells a C compiler to include stdio.h file before going to
actual compilation.
● The next line int main() is the main function where the program execution
begins.
● The next line /*...*/ will be ignored by the compiler and it has been put to
add additional comments in the program. So such lines are called
comments in the program.
● The next line printf(...) is another function available in C which causes the
message "Hello, World!" to be displayed on the screen.
● The next line return 0; terminates the main() function and returns the value
0.
Compile & Execute
● Open a text editor and add the above-mentioned code.
● Save the file as hello.c
● Open a command prompt and go to the directory where you have saved
the file.
● Type gcc hello.c and press enter to compile your code.
● If there are no errors in your code, the command prompt will take you to
the next line and would generate a.out executable file.
● Now, type a.out to execute your program.
● You will see the output "Hello World" printed on the screen.
Characteristic Feature of C Program
C keywords
Identifier
An identifier is used for any variable, function, data definition, labels in your program etc.

Before starting any language, you must at least know how you name an identifier.

In C language, an identifier is a combination of alphanumeric characters, i.e. first begin with a letter of the alphabet or
an underline, and the remaining are letter of an alphabet, any numeric digit, or the underline.

Rules for naming identifiers


The rules that must be followed while naming the identifiers are as follows −

● The case of alphabetic characters is significant. For example, using "TUTORIAL" for a variable is not the same
as using "tutorial" and neither of them is the same as using "TutoRial for a variable. All three refer to different
variables.
● There is no rule on how long an identifier can be. We can run into problems in some compilers, if an identifier is
longer than 31 characters. This is different for the different compilers.
● A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
● The first letter of an identifier should be either a letter or an underscore.
● You cannot use keywords like int, while etc. as identifiers.
Identifiers must be unique
Data Types
Data types in c refer to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in storage and how the bit
pattern stored is interpreted.
Variable
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a
specific type, which determines the size and layout of the variable's memory; the range of values that can be stored
within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a
letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive.

1 char
Typically a single octet(one byte). It is an integer type.

2 int
The most natural size of integer for the machine.

3 float
A single-precision floating point value.

4 double
A double-precision floating point value.

5 void
Represents the absence of type.
C programming language also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study
only basic variable types.

Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type and contains a list of one or more variables of that type as
follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names separated by commas.
Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;

The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create
variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes
have the value 0); the initial value of all other variables are undefined.

Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so
that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable
definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of
linking the program.
A variable declaration is useful when you are using multiple files and you define your variable in one of the files which
will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any
place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a
function, or a block of code.
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () { value of c : 30


value of f : 23.333334
/* variable definition: */
int a, b;
int c;
float f;

/* actual initialization */
a = 10;
b = 20;

c = a + b;
printf("value of c : %d \n", c);

f = 70.0/3.0;
printf("value of f : %f \n", f);

return 0;
}
Constants
Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called
literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a
string literal. There are enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified after their definition.

Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for
hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix
can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
0x4b /* hexadecimal */
078 /* Illegal: 8 is not an octal digit */
30 /* int */
032UU /* Illegal: cannot repeat a suffix */
30u /* unsigned int */
Following are other examples of various types of integer literals − 30l /* long */
85 /* decimal */ 30ul /* unsigned long
*/
0213 /* octal */
Floating Point Literal
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent
floating point literals either in decimal form or exponential form.
While representing decimal form, you must include the decimal point, the exponent, or both; and while representing
exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e
or E.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Character Constant
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g.,
'\u02C0').
There are certain characters in C that represent special meaning when preceded by a backslash for example, newline
(\n) or tab (\t).
#include <stdio.h>

int main() {
printf("Hello\tWorld\n\n");

return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
String Literal
String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character
literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using white spaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"


Defining Constants
There are two simple ways in C to define constants −
● Using #define preprocessor.
● Using const keyword.

The #define Preprocessor


Given below is the form to use #define preprocessor to define a constant −
#define identifier value

The following example explains it in detail −


#include <stdio.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
When the above code is compiled and
int main() { executed, it produces the following result −
int area; value of area : 50

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}
The const Keyword
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;

The following example explains it in detail −


#include <stdio.h>

int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
Array Declaration
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array
is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the
same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A
specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest
address to the last element.
Declaring Array
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an
array as follows −
type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be
any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement −
double balance[10];

Here balance is a variable array which is sufficient to hold up to 10 double numbers.


Initializing Array
You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

The number of values between braces { } cannot be larger than the number of elements that we declare for the
array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you
write −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example. Following is an example to assign a
single element of the array −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All arrays have 0 as the index of
their first element which is also called the base index and the last index of an array will be total size of the array
minus 1. Shown below is the pictorial representation of the array we discussed above −
Accessing an array element
An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array. For example −
double salary = balance[9];

The above statement will take the 10th element from the array and assign the value to salary variable. The
following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and
accessing arrays −
#include <stdio.h>

int main () {

int n[ 10 ]; /* n is an array of 10 integers */


int i,j;

/* initialize elements of array n to 0 */


for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}

/* output each array element's value */


Element[0] = 100
for (j = 0; j < 10; j++ ) { Element[1] = 101
Element[2] = 102
printf("Element[%d] = %d\n", j, n[j] );
Element[3] = 103
} Element[4] = 104
Element[5] = 105
Element[6] = 106
return 0; Element[7] = 107
} Element[8] = 108
Element[9] = 109
Expression
An expression is a combination of operators and operands which reduces to a single value. An operation is performed
on a data item which is called an operand. An operator indicates an operation to be performed on data.

For example, z = 3+2*1

z=5
● Primary expressions − It is an operand which can be a name, a constant
or any parenthesized expression. Example − c = a+ (5*b);
● Postfix expressions − In a postfix expression, the operator will be after
the operand. Example − ab+
● Prefix expressions − n a prefix expression, the operator is before the
operand. Example − +ab
● Unary expression − It contains one operator and one operand. Example −
a++, --b
● Binary expression − t contains two operands and one operator. Example
− a+b, c-d
● Ternary expression − It contains three operands and one operator. For
Example, Exp1? Exp2 − Exp3. If Exp1 is true, Exp2 is executed.
Otherwise, Exp3 is executed.

You might also like