C, Java, SQL 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 128

History Of C Language

History of C Language:
There were numerous programming languages that were developed before C language with
an objective to overcome the tedious architecture of old languages. Dennis Ritchie in 1972
developed a more user friendly language at bell laboratories of AT&T (American Telephone
& Telegraph), located in U.S.A. This language was considered as a High Level Language and
was named as C.
C inherited many behavior from its ancestors. Along with the inherited features, some more
unique features were developed in C that made it the most basic programming language
and the mother of all programming languages. Even today when there are several new and
modified programming languages already developed, C has its own importance and still
maintains its value.
Flow of Development of C Language:
YEAR LANGUAGE
1960 Algol
1967 BCPL
1970 B
1972 Traditional C
1978 K & R C
1989 ANSI C
1990 ANSI/ISO C
1999 C99

Features Of C
Features of C:
C is the most basic programming language and is among the first High level language which
is user interactive as well as machine understandable in nature. Some other features of C
are discussed below.
FEATURES DESCRIPTION
C is extensible in the sense that it can easily accept and and can easily
Extensible
adapt new features.
Fast speed of C results in quick compilation and execution of C programs
Fast Speed
within few seconds.
Machine Portability of C makes it machine independent and thus can be easily
Independent or executed in many machines, unlike the low level programming languages
Portable which are still machine dependent.
C is a high level language as it can be easily developed by a user.
Mid-level
However, C can also be used as a low level programming language to
programming
develop some system applications such as kernel, driver etc. Thus, it can
language
be better called as a mid-level language, instead of a high level language.
Dynamic memory allocation is a unique feature in C language, that helps
Memory
to manage the memory easily. For example, we can quickly and easily
Management
free the allocated memory at any time by calling the free() function.
Pointers in C helps to directly interact with the memory and can be easily
Pointers
used with memory, structures, functions, array etc.
The rich library of C contains various files that includes a collection of
Rich Library inbuilt functions, keywords, and processes to have a fast development
and execution.
Recursion means to call a function within that function only. C is the first
Recursion language to have this unique feature which ultimately improves the code
reusability.
The structured architecture of C, its rich set of library functions,
collections of different data types and its others unique features makes it
Simple to Learn
a user interactive and simple to learn and easy to understand
programming language.
Structured A structured programming language is the one which can be broken into
programming smaller parts. C supports this feature using multiple functions and is thus
language called as a Structured Programming Language.

How To Install C
How to install C:
For executing a C file in a system, C compiler is a must. Various C compilers are available
for downloading. Turbo C++ is among some common C compilers.
Steps to install Turbo C++:

1. Download Turbo C++ compiler.


2. Create a directory inside the C drive.
3. Extract the zip file inside Turbo C folder.
4. Double click on install.exe file in order to start installing the compiler.
5. Click on the INSTALL icon located inside the inside Turbo C folder.
6. Click on ENTER to allow installing.
7. Enter the drive as C and press ENTER for the INSTALL utility to copy files.
8. Select Start Installation to begin copying files to the hard drive of the system.
9. The compiler is successfully installed. Close the window.
10. Start the software again by clicking on the icon and write C programs.

First C Program
Lets print “Hello C” as the first C program and than understand it in detail.
#include <stdio.h>

void main()
{
printf ("Hello C!");
}
Output
Hello C!
Description:
#include <stdio.h> :
“#include” is a preprocessor directive used to include a library file in the code. The header
file “stdio.h” is included in the source code to use the pre-defined functions “printf” and
“scanf”.
void main() :
Void represents the data type of the main function which is a must for every C program.
{} :
{} represents the opening and closing of the main function.
printf (“Hello C!”); :
The printf function outputs the string on the console screen.
Compilation and Execution:
Click on Compile menu and then on Run menu or click ctrl+F9 directly, both for compile and
run.

Flow Of C Program
Execution Flow of C Program:
Execution of a C Program is a step by step process which is discussed below.
Preprocessors:
Before compilation, the preprocessor starts processing the preprocessors directives first and
generates an expanded source code.
Assembly Code:
The compiler than converts this expanded source code into an (.asm) assembly code.
Object Code:
After compilation, the assembler assembles the code and generates an (.obj) object code.
Executable Code:
After assembling, the linker links the object code to the library such as header files to
convert it into an (.exe) executable code.
Console Display:
The final step is to load the executable code into memory via a loader. THe executable code
is than executed and output is displayed on the console screen.
Example:
Hello.c Hello.i Hello.asm

Hello.obj Hello.exe CONSOLE

C Printf And Scanf


C printf() function:
The printf() function is an inbuilt library function in C language, which is used for output, i.e,
to print a given statement on the console. The printf() function is defined in stdio.h (header
file) in C library.
Syntax:
printf(“format string”,argument_list);

 Format string: It is a mandatory parameter which takes value as %d (integer), %c


(character), %s (string), %f (float) etc.
 Argument List: It is also a mandatory parameter which includes all the variables
that are required to print.

C scanf() function:
The scanf() function is an inbuilt library function in C language, which is used for input, i.e,
to read the input data from the console. The scanf() function is also defined in stdio.h
(header file) in C library.
Syntax:
scanf(“format string”,&argument_list);

 Format string: It is a mandatory parameter which takes value as %d (integer), %c


(character), %s (string), %f (float) etc.
 & (Ampersand): It is added just before the variable name which represents that
the data need to be feeded.
 Argument List: It is also a mandatory parameter which includes all the variables in
which the input data need to be feed.

Example:
#include<stdio.h>

void main()
{
int a, b;
printf ("Enter two numbers: ");
scanf ("%d, %d",&a,&b);
printf("Sum of x+y = %i", a+b);
}
Output
Enter two numbers: 2,3
Sum of x+y = 5

Variables In C
A variable is a temporary memory location that holds its data temporarily. C requires the
data type of the variable to be well defined at the time of variable declaration, according on
its value.
Syntax:
data_type variable_list;
Rules for using C Variables:

 C Variable name starts with a letter or underscore only; numbers and special
characters are restricted for this.
 C Variables name can contain alphanumeric characters and underscores only.
 C Variables name can not contain any white space within it.
 C Variables name should not be same as any reserved word or keyword already
defined in C library.

C Variables Types:
C Variable are classified according to the scope of the variable inside the code, i.e, the
portion of the script where the variable can be used. These are:
Local:
Local Variables can only be accessed within the function where it is declared.
Global:
Global Variables can only be declared outside the function and can be accessed by all the
functions.
Static:
Static Variables are declared with static keyword for a variable to retain its value between
multiple function calls.
External:
External Variables are declared with extern keyword for a variable to be shared in multiple
files.
Automatic:
Automatic Variables can be declared with auto keyword. Although, every variable declared
inside a function, by default, are automatic variables.
Example 1: Local declaration of Variables.
#include<stdio.h>

void main()
{
int a, b;
printf ("Enter two numbers: ");
scanf ("%d, %d",&a,&b);
printf("Sum of x+y = %i", a+b);
}
Output
Enter two numbers: 2,3
Sum of x+y = 5
Example 2: Global declaration of Variables.
#include<stdio.h>
int sum;

void main()
{
int a, b;
printf ("Enter two numbers: ");
scanf ("%d, %d",&a,&b);
sum = a+b;
printf("Sum of x+y = %i", sum);
}
Output
Enter two numbers: 2,3
Sum of x+y = 5

C Constants
C Constants are the identifiers that once defined, cannot be modified. C Constants can
either be defined using #define preprocessor or using const keyword. Like C Variables, C
Constants name can only be started with a letter or an underscore only.
C #define preprocessor:
Syntax:
#define Constant_name Constant_Value;

 Constant Name: This parameter is used to specify the name of the constant.
 Constant Value: This parameter is used to specify the value of the constant.

C const keyword:
C const keyword is another method to define constants during compilation.
Example 1: Defining C Constants using #define preprocessor
#include <stdio.h>
#define AGE 30
void main()
{
printf ("%d", AGE);
}
Output
30
Example 2: Defining C Constants using const keyword
#include <stdio.h>
void main()
{
const int AGE = 30;
printf ("%d", AGE);
}
Output
30

Data Types In C
C Data Types are used to define the type of data that is to be stored. C data types can be
classified into 4 groups:
● Basic Data Types:

1. Integer
2. Float
3. Double
4. Character

● Derived Data Types:

1. Array
2. Pointer
3. Structure
4. Union

● Enumeration Data Types:


Enum
● Void Data Types:
Void
Basic Data Types:
Integer: All the non-decimal numbers are called as Integers. Various forms of integers are
listed below.
SIZE (Byte)
Data Types RANGE
For 32 bit
short 2 −32,768 to 32,767
signed short 2 −32,768 to 32,767
unsigned short 2 0 to 65,535
int 2 −32,768 to 32,767
signed int 2 −32,768 to 32,767
unsigned int 2 0 to 65,535
short int 2 −32,768 to 32,767
signed short int 2 −32,768 to 32,767
unsigned short int 2 0 to 65,535
long int 4 -2,147,483,648 to 2,147,483,647
signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
Float:
Float represents all the decimal and exponential numbers. The float size is of 4 bytes.
Double:
Double also represents all the decimal and exponential numbers. Various forms of double
are listed below.
Data Types SIZE (Byte) For 32 bit
double 8
long double 10
Character:
Various forms of characters are listed below.
Data Types SIZE (Byte) RANGE
char 1 −128 to 127
signed char 1 −128 to 127
unsigned char 1 0 to 255

Example:
#include<stdio.h>

void main()
{
printf ("For 64 bit architecture\n");
printf ("\nSize of int: %d", sizeof(int));
printf ("\nSize of short: %d", sizeof(short));
printf ("\nSize of short int: %d", sizeof(short int));
printf ("\nSize of long int: %d", sizeof(long int));
printf ("\nSize of char: %d", sizeof(char));
printf ("\nSize of float: %d", sizeof(float));
printf ("\nSize of double: %d", sizeof(double));
printf ("\nSize of long double: %d", sizeof(long double));
}
Output
For 64 bit architecture

Size of int: 4
Size of short: 2
Size of short int: 2
Size of long int: 8
Size of char: 1
Size of float: 4
Size of double: 8
Size of long double: 16

Keywords In C
C Keywords:
There are a list of words already defined in C library. These reserved words are called as C
Keywords. Every keyword is defined to serve a specific purpose. These keywords when used
in C codes performs a specific operation during compilation. A Keyword in C is restricted to
be used as a variable, a function or an identifier.
Keywords used in C are listed below:

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Example:
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
Output
Hello World

C Operators
C Operators are used to perform operations on operands. Operands can be a variable or a
constant. The operators are divided into various groups on the basis of the basic operations
they perform.
Some of the basic operators are:
Arithmetic Operators:
The operators which are used to perform the arithmetical operations, are grouped together
as Arithmetic operators.
Operators Symbol
Addition +
Subtraction –
Multiplication *
Division /
Modulus %
Assignment Operators:
The operators which are used to assign values to a variable, are grouped together as
Assignment operators.
Operators Symbol
Equals To =
Added Value +=
Subtracted Value -=
Multiplicated Value *=
Divided Value /=
Modulus Value %=
Comparison Operators:
The operators which are used to compare two values, are grouped together as Comparison
operators.
Operators Symbol
Equal ==
Not equal !=
Greater than >
Less than <
Greater than or equal to >=
Less than or equal to <=
Logical Operators:
The operators which are used to perform logical operations, are grouped together as Logical
operators.
Operators Symbol
AND &&
OR ||
Precedence and Associativity of C Operators:
The precedence and associativity of different types of operators in C are listed below.
PRECEDENCE OPERATORS ASSOCIATIVITY
Postfix Operators () [] -> . ++ – – Left to Right
Unary Operators + – ! ~ ++ – – (type)* & sizeof Right to Left
Multiplicative Operators * / % Left to Right
Additive Operators +– Left to Right
Shift Operators << >> Left to Right
Relational Operators < <= > >= 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 Operator ?: Right to Left
Assignment Operators = += -= *= /= %=>>= <<= &= ^= |= Right to Left
Comma , Left to Right
Example:
#include <stdio.h>

int main()
{
int sum1 = 10+20*10-90*10+700;
int sum2 = (10+20)*10-(90*10)+700;
printf ("%d", sum1);
printf ("\n");
printf ("%d", sum2);

return 0;
}
Output
10
100

C Comments
C comments are used to give a brief description about any specific line of code or about a
module in the code to make the code more user-friendly.
C Comments can be of two types:

 Single line Comments


 Multi line Comments

Single Line Comments:


Single line comments can be used for commenting a line of the code or to write a single line
description about the code. The lines starting with // is considered as single line comment.
Multi Line Comments:
Multi line comments can be used for commenting a part of the code or to write a multiple
lines description about the code. The lines enclosed between /* */ are considered as multi
line comments.
Example:
#include <stdio.h>

int main()
{
// Performing Arithmetic Operations without using brackets.
int sum1 = 10+20*10-90*10+700;

/* Performing Arithmetic Operations


using brackets to clarify the expression.*/

int sum2 = (10+20)*10-(90*10)+700;


printf ("%d", sum1);
printf ("\n");
printf ("%d", sum2);

return 0;
}
Output
10
100

C Escape Sequence
A sequence of characters starting with backslash ( \ ) that performs a specified function,
which is already defined by C, is called as an escape sequence in C. It is named so as it
doesn’t represent itself as a character, when it is used inside a string.
Some of the C Escape Sequence are listed below.
ESCAPE SEQUENCE USES
\a Alarm or Beep
\b Backspace
\\ Backslash
\r Carriage Return
\” Double Quote
\f Form Feed
\xhh Hexadecimal Number
\n New Line
\0 Null
\nnn Octal Number
\? Question Mark
\’ Single Quote
\t Tab (Horizontal)
\v Vertical Tab

Example:
#include <stdio.h>
void main()
{
printf ("\tI love my INDIA.\vINDIA is my Country.\nMy Country is my
Identity.");
}
Output
I love my INDIA.
INDIA is my Country.
My Country is my Identity.

C If Else
C If Else statement is a conditional statement, which can be used in various forms to check
a condition or multiple conditions and to perform the specified action or actions, if the
particular condition is true. These are:
if :
If statement is used to perform an action if a single condition is true.
Syntax:
if (condition)
{
Execute this code if condition is true; else nothing to be executed;
}
..else:
If else statement is used to perform an action if a single condition is true and to perform
another action if that condition is false.
Syntax:
if (condition)
{
Execute this code if condition is true;
}
else
{
Execute this code if condition is false;
}
..else if….else:
If elseif else statement is used to perform different actions for different conditions.

Syntax:
if (condition)
{
Execute this code if this condition is true;
}
else if (condition)
{
Execute this code if this condition is true;
}
else
{
Execute this code if all the conditions are false;
}
Example 1: Example of if statement
#include <stdio.h>

void main()
{
int sum = 200;

if (sum <= 200)


printf ("You Lose!");
}
Output
You Lose!
Example 2: Example of if..else statement
#include <stdio.h>

void main()
{
int sum = 100;

if (sum <= 200)


printf ("You Lose!");
else
printf ("You Won!");
}
Output
You Won!
Example 3: Example of if..else if..else statement
#include <stdio.h>

void main()
{
int sum = 200;

if (sum <200)
printf ("You Lose!");
else if (sum = 200)
printf ("Match Draw!");
else
printf ("You Won!");
}
Output
Match Draw!

C Switch
C Switch statement is a conditional statement, which is used to choose one of the action to
perform from the multiple actions, relative to the true condition.
Syntax:
switch (expression)
{
case value1:
code to be executed if expression=value1;
break;

case value2:
code to be executed if expression=value2;
break;

case value3:
code to be executed if expression=value3;
break;

default:
code to be executed if expression is different from all values;
}

Example:
#include <stdio.h>

void main()
{
int num = 5;
switch (num)
{
case 1:
printf ("One!");
break;
case 2:
printf ("Two!");
break;
case 3:
printf ("Three!");
break;
case 4:
printf ("Four!");
break;
case 5:
printf ("Five!");
break;
default:
printf ("Other!");
}
}
Output
Five!

C For Loop
C For Loop is a loop statement which can be used in various forms to execute a block of
code continuously as long as the condition of the loop is true, and stops only when the
condition fails. These are:
For Loop :
For loop is used to execute a group of action only for a specified number of times.
Syntax:
for(initialization; condition; increment/decrement)
{
code to be executed till the condition is true;
}
Nested For Loop :
Nested For loop is For loop inside a For loop and so on which is used to run multiple loop
conditions.
Syntax:
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
code to be executed till the condition is true;
}
}
Example 1: Example of For loop
#include <stdio.h>

void main()
{
int i;

for (i = 0; i <= 10; i++)


{
printf ("%d", i);
printf ("\n");
}
}
Output
0
1
2
3
4
5
6
7
8
9
10
Example 2: Example of Nested For loop
#include <stdio.h>

void main()
{
int i,j;
for (i = 1; i <= 10; i++)
{
printf ("%d", i);
printf ("\n");
for (j = 1; j <= i; j++)
{
printf ("%d", j);
}
printf ("\n");
}
}
Output
1
1
2
12
3
123
4
1234
5
12345
6
123456
7
1234567
8
12345678
9
123456789
10
12345678910

C While Loop
C While Loop is a loop statement which can be used in various forms to execute a block of
code continuously as long as the condition of the loop is true, and stops only when the
condition fails. These are:
While Loop :
While loop is used to execute a group of action as long as the specified condition is true.
Syntax:
while (condition)
{
code to be executed if the condition is true;
}
Nested While Loop :
Nested While loop is While loop inside a While loop and so on which is used to run multiple
loop conditions.
Syntax:
while (condition)
{
while (condition)
{
code to be executed if the condition is true;
}
}
Infinitive While loop :
Infinitive While loop is a While loop with condition 1 and thus running for infinite number of
times.
Syntax:
while (1)
{
code to be executed;
}

Example of While loop


#include <stdio.h>

void main()
{
int i = 1;

while (i <= 10)


{
printf ("%d", i);
printf ("\n");
i++;
}
}
Output
1
2
3
4
5
6
7
8
9
10

C Do While Loop
C Do While Loop is a loop statement which is used to execute a block of code continuously
as long as the condition of the loop is true, and stops only when the condition fails like other
loop statements.
The unique feature of Do While loop is that it is used to execute a block of code at least
once and then to repeat the actions as long as the specified condition is true.

Syntax:
do
{
code to be executed;
}
while (condition);

Example 1: When the While condition is true


void main()
{
int i = 1;

do
{
printf ("%d", i);
i++;
}
while (i <= 10);
}
Output
12345678910
Example 2: When the While condition is false
void main()
{
int i = 11;

do
{
printf ("%d", i);
i++;
}
while (i <= 10);
}
Output
11

C Break
C break statement is used to break the execution of current loop in between the loop or to
prevent the code to check the next switch case.
Break statement breaks the continuity of the containing loop only, i.e, external loops will
not get affected because of Break statement in inner loop.
Syntax:
loop/conditions statements
{
statements;
break;
}
Example 1: Use of Break Statement in Switch Case
#include <stdio.h>
void main()
{
int num = 5;
switch (num)
{
case 1:
printf ("One!");
break;
case 2:
printf ("Two!");
break;
case 3:
printf ("Three!");
break;
case 4:
printf ("Four!");
break;
case 5:
printf ("Five!");
break;
default:
printf ("Other!");
}
}
Output
Five!
Example 2: Use of Break Statement in For Loop
#include <stdio.h>

void main()
{
int i;

for (i = 1; i <= 10; i++)


{
printf ("%d", i);
printf ("\t");
if (i == 5)
break;
}
}
Output
1 2 3 4 5

C Continue
C Continue statement is used to skip the execution of current iteration in between the loop.
Continue statement controls the containing loop only, i.e, external loops will not get affected
because of Continue statement in inner loop.
Syntax:
loop/conditions statements
{
statements;
continue;
}
Example:
#include <stdio.h>

void main()
{
int i,j;

for (i = 1; i <= 10; i++)


{
if (i == 5)
continue;
printf ("%d", i);
printf ("\t");
}
}
Output
1 2 3 4 6 7 8 9 10

C Goto
C goto statement is used to jump to a specified label in the code every time, without any
condition.
Syntax:
loop/conditions statements
{
statements;
goto;
}
Example:
#include <stdio.h>

void main()
{
int i,n;
printf ("Enter a number: ");
scanf ("%d",&n);

less:
printf ("less than 5");

if (i < 5)
goto less;
else
{
printf ("%d", i);
}
}
Output
Enter a number: 4
less than 5

Type Casting In C
Type casting in C simply means to convert one data type into other. C facilitates with a
special operator named (type) which serves the purpose of type casting, where type
represents the required data type.
Syntax:
(type) value;
Example:
#include<stdio.h>
void main()
{
char value= (char)66;
printf("Value : %c\n", value );
}
Output
Value : B

C Functions
A function is a piece of code that can be used repeatedly in a C program. A function is
mainly of two types:

 Built in Functions; which are already defined in C Library.


 User Defined Functions; which are created and defined by users.

Syntax:
Return_type functionName(parameters)
{
code to be executed;
}

Rules for using Functions:

 Void return type is used when nothing need to be returned from the function.
 Functions can also be used to return value. Return type such as int, long, char etc.
are used to return a value from the function of the given type.
 A function starts with an opening curly brace ( { ) and ends with a closing curly
brace ( } ).
 Arguments are the variables, inside the parentheses, after the function name which
is used to pass informations to functions.
 For multiple arguments, comma should be used for separation.
 Default argument value can also be specified in a function. If no argument is
specified, the function will take the default argument.

Calling a Function in C:
In order to get the value returned from the function, the function need to be called in the
program.
Syntax:
Variable_name = function_name (parameters_values);
Example:
#include<stdio.h>
int writeMsg()
{
printf ("My First Program using Function!");
return 0;
}

void main()
{
writeMsg();
}
Output
My First Program using Function!

C Call: Value & Reference


Call: Value & Reference:
Calling a function in C and passing values to that function can be done in two ways:

 Call by Value
 Call by Reference

Call by Value Call by Reference


Original value of the function parameter Original value of the function parameter is
is not modified. modified.
In this method, we pass a copy of the In this method, we pass an address of the value
value to the function. to the function.
The value to be passed to the function is The value to be passed to the function is stored
locally stored. at the location same as the address passed.
The value changed inside the function, The value changed inside the function, changes
changes for the current function only. for both inside as well as outside the function.
Actual and Formal arguments have Actual and Formal arguments shares the same
unique address spaces. address space.

Example 1: Example for Call by Value.


#include<stdio.h>
int sum(int a, int b)
{
int c;
c = a+b;
return c;
}

void main()
{
int x = 100;
int y = 200;
int add;
add = sum(x,y);
printf ("%d + %d = %d", x,y,add);
}
Output
100 + 200 = 300
Example 2: Example for Call by Value.
#include<stdio.h>
int sum(int *a, int *b)
{
int *c;
*c = *a + *b;
return *c;
}

void main()
{
int x = 100;
int y = 200;
int add;
add = sum(&x,&y);
printf ("%d + %d = %d", x,y,add);
}
Output
100 + 200 = 300

Recursion In C
When a function calls itself within its function block, it is called as self calling by a function.
This whole process of self calling by a function is often termed as Recursion. Recursion is
used to create a loop like behavior using a function and without using loop statements.
Syntax:
Return_type function_Name(parameters)
{
code to be executed;
function_Name(parameters);
}
Example: Sum of first 10 Natural Numbers using Recursion.
#include<stdio.h>
int sum(int n)
{
if (n > 0)
return (n + sum(n-1));
}

void main()
{
int add;
add = sum(10);
printf ("Sum of first 10 natural numbers = %d", add);
}
Output
Sum of first 10 natural numbers = 55

C Storage Classes
A Storage class in C represents the scope of a variable within the program. The storage
classes in C are discussed below:

Storage Storage Default


Scope Life-time Features
Classes Place Value
auto RAM Garbage Local Within function Default storage class.
Till the end of
extern RAM 0 Global Visible to all the programs.
main program
Till the end of Retains value between
static RAM 0 Local
main program multiple functions call.
Faster access than other
register Register Garbage Local Within function
variables.

Example:
#include<stdio.h>
void demo()
{
static int i=0;
register int j=0;
auto int k=0;
i++;
j++;
k++;

printf("i = %d\n", i);


printf("j = %d\n", j);
printf("k = %d\n", k);
}

void main()
{
demo();
printf ("\n");
demo();
printf ("\n");
demo();
}
Output
i = 1
j = 1
k = 1

i = 2
j = 1
k = 1

i = 3
j = 1
k = 1

C 1-D Array
An array is a single variable which can store multiple values at a time. Thus, C array is used
to hold many values under a single name. These values can be accessed the by referring to
their index number.
Syntax:
data_type arrayName [arraySize];
Or
data_type arrayName [arraySize] = array{value 1, value 2, …};
Advantages of using Array in C:

 Single variable need to be declared, instead of multiple variable, making the code
user friendly.
 Less number of lines needed in a code.
 Traversing of all the elements is easy.
 Functions like sorting can be easily applied to all the elements.

Example: Printing Table of 5.


#include<stdio.h>

void main()
{
int table[10] = {5,10,15,20,25,30,35,40,45,50};
int i;
for (i=1;i<11;i++)
{
printf ("5 * %d = %d", i,table[i-1]);
printf ("\n");
}
}
Output
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

C Multi Dimensional Array


A multidimensional array is an array containing two, three, four, five, or more arrays. The
increasing number of dimensions, increases the code complexity for the developers. The
most popular arrays are single, two and three dimensional arrays.
Two dimensional Arrays:
A C two-dimensional array can be defined as an array of arrays that needs two indices for
every element.
Three dimensional Arrays:
A C three-dimensional array can be defined as an array of arrays of arrays that needs three
indices for every element.
Example: Accessing the elements of a two dimensional array.
#include <stdio.h>
#include<stdlib.h>

void main()
{

int a[10][10],b[10][10],c[10][10],r1,c1,r2,c2,i,j;

printf("Enter the number of rows in first matrix: ");


scanf("%d",&r1);

printf("Enter the number of columns in first matrix: ");


scanf("%d",&c1);

printf("Enter the first matrix: \n");

for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}

printf("Enter the number of rows in second matrix: ");


scanf("%d",&r2);
printf("Enter the number of columns in second matrix: ");
scanf("%d",&c2);

printf("Enter the second matrix: \n");

for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}

if ((r1==r2) & (c1==c2))


{

for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j] = 0;
c[i][j] += a[i][j] * b[i][j];
}
}

printf ("Matrix after Addition:\n");


for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf ("%d",c[i][j]);
printf ("\n");
}
}
}

else
printf ("Addition not possible.");
}
Output
Enter the number of rows in first matrix: 2
Enter the number of columns in first matrix: 2
Enter the first matrix:
1
2
3
4
Enter the number of rows in second matrix: 2
Enter the number of columns in second matrix: 2
Enter the second matrix:
5
4
3
2
Matrix after Addition:
6
6
6
6

C Array To Function
Arguments are the variables, inside the parentheses, after the function name which is used
to pass informations to functions. Beside passing variables and pointers, arrays can also be
passed as a function parameter or argument.
Syntax:
Return_type functionName (Data_type array Name[])
{
code to be executed;
}
Example:
#include<stdio.h>

int maximum(int a[],int size)


{
int max = a[0];
int i=0;
for(i=1;i<size;i++)
{
if(max < a[i])
max = a[i];
}
return max;
}

void main()
{
int i=0,max=0;
int array[] ={9,52,77,635,889,679,6,54,78,34};

printf ("List of Numbers:\n");


for(i=0;i<10;i++)
{
printf ("%d",array[i]);
printf ("\n");
}

max = maximum(array,10);
printf("\nLargest Number is: %d",max);
}
Output
List of Numbers:
9
52
77
635
889
679
6
54
78
34

Largest Number is: 889

C Pointers
C pointers can be defined as a variable, pointing towards the address of a value.
Syntax:
Data_type *variable_Name;
Advantages of using Pointers in C:

 Improves the performance.


 Frequently used in arrays, structures, graphs and trees.
 Less number of lines needed in a code.
 Useful in accessing any memory location.
 Used in Dynamic Memory Allocation.

NULL Pointer:
NULL pointers either have no value or NULL value assigned to it.
Example:
#include<stdio.h>
int sum(int *a, int *b)
{
int *c;
*c = *a + *b;
return *c;
}

void main()
{
int x = 100;
int y = 200;
int add;
add = sum(&x,&y);
printf ("%d + %d = %d", x,y,add);
}
Output
100 + 200 = 300
C Pointer To Pointer
C pointers can be defined as a variable, pointing towards the address of a value. When a
pointer refers to the address of another pointer, it is called as Pointer to Pointer in C.
Syntax:
Data_type **variable_Name;
Example:
#include<stdio.h>

void main()
{
int n = 60784;
int *a;
int **b;
a = &n;
b = &a;

printf("n = %d \n",n);
printf("a = %x \n",a);
printf("b = %x \n",b);
printf("&n = %x \n",a);
printf("&a = %x \n",b);
}
Output
n = 60784
a = fef63734
b = fef63738
&n = fef63734
&a = fef63738

C Pointer Arithmetic
Pointer Arithmetic in C:
C pointers can be defined as a variable, pointing towards the address of a value. C also
facilitates Arithmetic operations with Pointers. Some of these are:
C Pointer Increment:
Incrementing a pointer in C simply means to increase the pointer value step by step to point
to the next location.
Logic:
Next Location = Current Location + i * size_of(data type)
Example 1: Example for C Pointer Increment.
#include<stdio.h>

void main()
{
int n = 10;
int *a;
a = &n;
printf("current address = %x \n",a);
a = a+1;
printf("next address = %x \n",a);
}
Output
current address = 5deb5ffc
next address = 5deb6000
C Pointer Decrement:
Decrementing a pointer in C simply means to decrease the pointer value step by step to
point to the previous location.
Logic:
Next Location = Current Location – i * size_of(data type)
Example 2: Example for C Pointer Decrement.
#include<stdio.h>

void main()
{
int n = 10;
int *a;
a = &n;
printf("current address = %x \n",a);
a = a-1;
printf("next address = %x \n",a);
}
Output
current address = d460f58c
next address = d460f588
C Pointer Addition:
Addition in pointer in C simply means to add a value to the pointer value.
Logic:
Next Location = Current Location + (Value To Add * size_of(data type))
Example 3: Example for C Pointer Addition.
#include<stdio.h>

void main()
{
int n = 10;
int *a;
a = &n;
printf("current address = %x \n",a);
a = a + 4;
printf("next address = %x \n",a);
}
Output
current address = bfdcd58c
next address = bfdcd59c
C Pointer Subtraction:
Subtraction from a pointer in C simply means to subtract a value from the pointer value.
Logic:
Next Location = Current Location – (Value To Add * size_of(data type))
Example 4: Example for C Pointer Subtraction.
#include<stdio.h>

void main()
{
int n = 10;
int *a;
a = &n;
printf("current address = %x \n",a);
a = a - 2;
printf("next address = %x \n",a);
}
Output
current address = f2fd491c
next address = f2fd4914

C Dynamic Memory Allocation


In Static Memory Allocation, memory is allocated at compile time, that can’t be modified
while executing program and is generally used in array.
In Dynamic Memory Allocation, memory is allocated at run time, that can be modified while
executing program and is generally used in linked list.
Methods used for Dynamic memory allocation:
Method Syntax Uses
P = (cast_type*) To allocate a single block of requested
malloc()
malloc(byte_size) memory.
P = (cast_type*) calloc(number, To allocate multiple block of requested
calloc()
byte_size) memory.
P = realloc(P, new_size) To allocate the memory occupied by malloc()
realloc()
or calloc() function.
free(P)
free() To free the dynamically allocated memory.

Example:
#include<stdio.h>
#include<stdlib.h>

void main()
{
int n = 10;
int *a, *b;
a = (int*)malloc(n*sizeof(int));
printf("current address = %x \n",a);

b = (int*)calloc(n,sizeof(int));
printf("current address = %x \n",b);
}
Output
current address = 3acba260
current address = 3acbb2a0
String In C
C Strings:
A sequence of characters, internally stored in the form of an array of characters is called as
string.
Declaration of String:
In C, a string can be specified in two ways:
Character Array:
A string declared as an array, where each character represents an element of that array, is
called as Character Array.
Syntax:
char array_Name[] = {char1,char2,char3………};
String Literal:
A string declared as an array, where the whole string represents a complete array, is called
as String Literal.
Syntax:
char array_Name[] = “stringValue”
Example :
#include<stdio.h>
#include <string.h>

void main()
{
char chr[]={'H', 'E', 'L', 'L', 'O', ' ', 'C', '\0'};
char str[]="HELLO C";
printf("String in form of character array: %s\n", chr);
printf("String in form of string literal: %s\n", str);
}
Output
String in form of character array: HELLO C
String in form of string literal: HELLO C

C Gets() & Puts()


C gets() function:
C library facilitates a special function to read a string from a user. This function is
represented as gets() function and is defined in the <stdio.h> header file of C.
C puts() function:
C library also facilitates a special function to print a string on the console screen. This
function is represented as puts() function and is also defined in the <stdio.h> header file of
C.
Example:
#include<stdio.h>
#include <string.h>

void main()
{
char day[10];
printf("Enter current week day: \n");
gets(day);
printf("Today is: ");
puts(day);
}
Output
Enter current week day: THURSDAY
Today is: THURSDAY

C String Functions
String Functions are the built-in functions provided by C to operate and manipulate a string.
C provides a number of string functions. Some of the MOST USED string functions are listed
below:
FUNCTION SYNTAX USES
strlwr() strlwr (string ) Converts a string to lowercase letters.
strupr() strupr (string ) Converts a string to uppercase letters.
strcpy() strcpy(destination, source) Copies a string from source to destination.
strcat() strcat(string1, string2) Concatenates two strings.
strcmp() strcmp(string1, string2) Compares two strings, if same, it returns 0.
strrev() strrev (string ) Reverses a string.
strlen() strlen (string name) Returns the length of a string.
Example:
#include<stdio.h>
#include <string.h>
#include <stdbool.h>

void main()
{
char str1[10] = "Hello C. ";
char str2[20] = "Hello World.";
char str3[30];
bool a;
int b;

strcpy(str3, str2);
puts(str3);
strcat(str1, str2);
puts(str1);
a = strcmp(str1, str2);
printf ("%d\n",a);
b = strlen (str1);
printf ("%d\n",b);
}
Output
Hello World.
Hello C. Hello World.
1
21
C Strlen()
C strlen():
String Functions are the built-in functions provided by C to operate and manipulate a string.
C strlen() function returns the length of a string.
Syntax:
strlen (string name)
Example:
#include<stdio.h>
#include <string.h>

void main()
{
char str[10] = "Hello C.";
int b;
b = strlen (str);
printf ("%d\n",b);
}
Output
8

C Strcpy()
C strcpy():
String Functions are the built-in functions provided by C to operate and manipulate a string.
C strcpy() function copies a string from source to destination.
Syntax:
strcpy(destination, source)
Example:
#include<stdio.h>
#include <string.h>
#include <stdbool.h>

void main()
{
char str1[10] = "Hello C.";
char str2[10];

strcpy(str2, str1);
puts(str2);
}
Output
Hello C.

C Strcat()
C strcat():
String Functions are the built-in functions provided by C to operate and manipulate a string.
C strcat() function concatenates two strings.
Syntax:
strcat(string1, string2)
Example:
#include<stdio.h>
#include <string.h>

void main()
{
char str1[10] = "Hello C. ";
char str2[20] = "Hello World.";
strcat(str1, str2);
puts(str1);
}
Output
Hello C. Hello World.

C Strcmp()
C strcmp():
String Functions are the built-in functions provided by C to operate and manipulate a string.
C strcmp() function compares two strings and returns 0 value if the strings are same, else it
returns 1.
Syntax:
strcmp(string1, string2)
Example:
#include<stdio.h>
#include <string.h>
#include <stdbool.h>

void main()
{
char str1[10] = "Hello C. ";
char str2[20] = "Hello World.";
bool a;

a = strcmp(str1, str2);
printf ("%d\n",a);
}
Output
1

C Strrev()
C strrev():
String Functions are the built-in functions provided by C to operate and manipulate a string.
C strrev() function reverses a string.
Syntax:
strrev (string )
Example:
#include<stdio.h>
#include <string.h>
void main()
{
char str[10] = "Hello C.";
printf("%s",strrev(str));
}
Output
.C olleH

C Strlwr()
C strlwr():
String Functions are the built-in functions provided by C to operate and manipulate a string.
C strlwr() function converts a string to lowercase letters.
Syntax:
strlwr (string )
Example:
#include<stdio.h>
#include <string.h>

void main()
{
char str[10] = "Hello C.";
printf("%s",strlwr(str));
}
Output
hello c.

C Strupr()
C strupr():
String Functions are the built-in functions provided by C to operate and manipulate a string.
C strupr() function converts a string to uppercase letters.
Syntax:
strupr (string )
Example:
#include<stdio.h>
#include <string.h>

void main()
{
char str[10] = "Hello C.";
printf("%s",strupr(str));
}
Output
HELLO C.

C Strstr()
C strstr():
String Functions are the built-in functions provided by C to operate and manipulate a string.
C strstr() function returns substring from first match till the last character.
Syntax:
char *strstr(const char *string, const char *match)
Example:
#include<stdio.h>
#include <string.h>

void main()
{
char str[50]="Hello! C you there C.";
char *s;

s = strstr(str,"C");
printf("Substring is: %s",s);
}
Output
Substring is: C you there C.

C Math Functions
C Math Functions:
Math functions and constants are already defined in the C library, in <math.h> header file,
which can be used to perform mathematical calculations.
C provides various math functions including;
abs() function:
This function is used to get an absolute value of a number.
Syntax:
abs ( number )
ceil() function:
This function is used to get a round up value; greater than or equal to given number.
Syntax:
ceil ( number )
floor() function:
This function is used to get a round down value; less than or equal to given number.
Syntax:
floor ( number )
sqrt() function:
This function is used to get the square root of a number.
Syntax:
sqrt ( number )
pow() function:
This function is used to get the value of base raised to the power of exponent.
Syntax:
pow ( base, exponent )
There are numerous other functions defined by C which are used to perform mathematical
operations.
Example:
#include<stdio.h>
#include <math.h>

void main()
{
printf("\n%f",ceil(56.698));
printf("\n%f",floor(78.67));
printf("\n%f",sqrt(2));
printf("\n%f",pow(6,2));
printf("\n%d",abs(-897));
}
Output
57.000000
78.000000
1.414214
36.000000
897

C Structure
C Structure:
Among other data types like int, array, string, etc, C facilitates a very unique data type that
can hold elements of different data types in a single variable and thus is often called as an
user-defined data type.
Any information about a person, class or product, etc. is best stored in a structure where
each element is often called as a member of a structure.
Syntax:
{
data_type element 1;
data_type element 2;
.
.
data_type element N;
};
Declaring a Structure Variable:
● Using struct keyword:
Structure variable can be declared by using struct keyword within the main function. This
way of declaration provides a flexibility of multiple declaration. Thus it is best preferred, if
no. of variables varies.
● At the time of defining structure:
Structure variable can also be declared at the time of defining structure. This way of
declaration decreases the number of coe lines. Thus it is best preferred, if no. of variables
are fixed.
Accessing a Structure Member:
To access a structure member, either use a member or a dot operator (.) or a structure
pointer operator (->).
Example:
#include<stdio.h>
#include <string.h>

struct student
{
int roll_no;
char name[30];
}s;
void main( )
{

s.roll_no = 1;
strcpy(s.name, "Jai");

printf( "Student Enrollment No. : %d\n", s.roll_no);


printf( "Student Name : %s\n", s.name);
}
Output
Student Enrollment No. : 1
Student Name : Jai

C Array Of Structures
C Array of Structures:
In order to store multiple data of different data types, an array of structures is used.
Example:
#include<stdio.h>
#include <string.h>

struct student
{
int roll_no;
char name[30];
};

void main( )
{
struct student s[3];
int i;

s[0].roll_no = 1;
strcpy(s[0].name, "Vibhuti Singh");
s[1].roll_no = 2;
strcpy(s[1].name, "Yashvendra Singh");
s[2].roll_no = 3;
strcpy(s[2].name, "Pankaj Mittal");

for(i=0;i<3;i++)
{
printf( "Student Enrollment No. : %d\n", s[i].roll_no);
printf( "Student Name : %s\n\n", s[i].name);
}
}
Output
Student Enrollment No. : 1
Student Name : Vibhuti Singh

Student Enrollment No. : 2


Student Name : Yashvendra Singh
Student Enrollment No. : 3
Student Name : Pankaj Mittal

C Nested Structure
C Nested structure:
A C Nested Structure can be defined in two ways:
By separate structure:
Defining a Nested Structure by separate structure simply means to use a structure inside
another structure as a member of that structure. In this way, a single structure can be used
in many structures.
Example 1:
#include<stdio.h>
#include <string.h>

struct Date
{
int dd;
int mm;
int yyyy;
};

struct student
{
int roll_no;
char name[30];
struct Date doj;
}s;

void main( )
{
s.doj.dd=21;
s.doj.mm=9;
s.doj.yyyy=2014;
s.roll_no = 1;
strcpy(s.name, "Vibhuti Singh");

printf( "Student Date of Joining (D/M/Y) : %d/%d/%d\n",


s.doj.dd,s.doj.mm,s.doj.yyyy);
printf( "Student Enrollment No. : %d\n", s.roll_no);
printf( "Student Name : %s\n\n", s.name);
}
Output
Student Date of Joining (D/M/Y) : 21/9/2014
Student Enrollment No. : 1
Student Name : Vibhuti Singh
By Embedded structure
Defining a Nested Structure by embedded structure simply means to define a structure
inside another structure. In this way, number of code lines decreases, however, a single
structure can not be used in other structures.
Example 2:
#include<stdio.h>
#include <string.h>

struct student
{
int roll_no;
char name[30];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}s;

void main( )
{
s.doj.dd=21;
s.doj.mm=9;
s.doj.yyyy=2014;
s.roll_no = 1;
strcpy(s.name, "Vibhuti Singh");

printf( "Student Date of Joining (D/M/Y) : %d/%d/%d\n",


s.doj.dd,s.doj.mm,s.doj.yyyy);
printf( "Student Enrollment No. : %d\n", s.roll_no);
printf( "Student Name : %s\n\n", s.name);
}
Output
Student Date of Joining (D/M/Y) : 21/9/2014
Student Enrollment No. : 1
Student Name : Vibhuti Singh
Accessing a member of Nested Structure:
Syntax:
Outer_Structure.Nested_Structure.member

C File Handling
C File Handling:
File handling simply means to open a file and to process it according to the required tasks.
C facilitates several functions to create, read, write, append, delete and close files.
❏ Open File:
To open a file in C, fopen() function is used.
❏ Close File:
To close a file in C, fclose() function is used.
❏ Read File:
To read a file in C, fscanf() function is used.
❏ Write File:
To write a file in C, fprintf() function is used.
C Open File:
To open a file in C, fopen() function is used. In general, fopen() function accepts two
parameters:
Filename: This parameter specifies the name of the file to be opened.
Mode: This parameter specifies the mode in which the file should be opened.
Syntax:
FILE *fopen( const char * filename, const char * mode );
MODES of fopen function:
*mode FILE MODE DESCRIPTION
Text Read only
r Pointer starts from the beginning of the file.
File mode
Text Write only Overwrites the existing file or creates a new file if it doesn’t
w
File mode exist. Pointer starts from the beginning of the file.
Text Write only Continues writing in the existing file or creates a new file if it
a
File mode doesn’t exist. Pointer starts from the end of the file.
Text Read Write
r+ Pointer starts from the beginning of the file.
File mode
Text Read Write Overwrites the existing file or creates a new file if it doesn’t
w+
File mode exist. Pointer starts from the beginning of the file.
Text Read Write Continues writing in the existing file or creates a new file if it
a+
File mode doesn’t exist. Pointer starts from the end of the file.
Binary Read only
rb Pointer starts from the beginning of the file.
File mode
Binary Write only Overwrites the existing file or creates a new file if it doesn’t
wb
File mode exist. Pointer starts from the beginning of the file.
Binary Write only Continues writing in the existing file or creates a new file if it
ab
File mode doesn’t exist. Pointer starts from the end of the file.
Binary Read Write
rb+ Pointer starts from the beginning of the file.
File mode
Binary Read Write Overwrites the existing file or creates a new file if it doesn’t
wb+
File mode exist. Pointer starts from the beginning of the file.
Binary Read Write Continues writing in the existing file or creates a new file if it
ab+
File mode doesn’t exist. Pointer starts from the end of the file.
Example:
#include <stdio.h>
void main()
{
FILE *f;
f = fopen("file.txt", "w");
fprintf(f, "Reading data from a file is a common feature of file
handling.\n");
fclose(f);

char arr[50];
f = fopen("file.txt", "r");
while(fscanf(f, "%s", arr)!=EOF){
printf("%s ", arr);
}
fclose(f);
}
Output
Reading data from a file is a common feature of file handling.

C Fprintf() Fscanf()
File handling simply means to open a file and to process it according to the required tasks.
Writing data in a file is one of the common feature of file handling. In C, there are various
modes that facilitates different ways and features of writing data into a file, including: w,
r+, w+, a+, wb, rb+, wb+, or ab+ mode. C also supports some functions to write to a file.
C Write File functions are:

 C fprintf()
 C fputs()
 C fputc()
 C fputw()

C fprintf() function:
To write a file in C, fprintf() function is used.
Syntax:
fprintf(FILE *stream, const char *format [, argument, …])
Example 1: Example of fprintf() function.
#include <stdio.h>
void main()
{
FILE *f;
f = fopen("file.txt", "w");
fprintf(f, "Reading data from a file is a common feature of file
handling.\n");
printf ("Data Successfully Written to the file!");
fclose(f);
}
Output
Data Successfully Written to the file!
C Read File:
Reading data from a file is another common feature of file handling. In C, there are various
functions that facilitates different ways and features of reading data from a file, including:
reading all file data at a single go, reading the file data line by line and even to read the file
data character by character.
C Read File functions are:

 C fscanf()
 C fgets()
 C fgetc()
 C fgetw()

❏ C fscanf() function:
To read a file in C, fscanf() function is used.
Syntax:
fscanf(FILE *stream, const char *format [, argument, …])
Example 2: Example of fscanf() function.
#include <stdio.h>
void main()
{
FILE *f;
f = fopen("file.txt", "w");
fprintf(f, "Reading data from a file is a common feature of file
handling.\n");
fclose(f);

char arr[50];
f = fopen("file.txt", "r");
while(fscanf(f, "%s", arr)!=EOF)
{
printf("%s ", arr);
}
fclose(f);
}
Output
Reading data from a file is a common feature of file handling.

C Fputc() Fgetc()
C Write File:
File handling simply means to open a file and to process it according to the required tasks.
Writing data in a file is one of the common feature of file handling. In C, there are various
modes that facilitates different ways and features of writing data into a file, including: w,
r+, w+, a+, wb, rb+, wb+, or ab+ mode. C also supports some functions to write to a file.
C Write File functions are:

 C fprintf()
 C fputs()
 C fputc()
 C fputw()

C fputc() function:
To write a single character into a file in C, fputc() function is used.
Syntax:
fputc(char, FILE *stream)
Example 1: Example of fputc() function.
#include <stdio.h>
void main()
{
FILE *f;
f = fopen("file.txt", "w");
fputc('Z',fp);
printf ("Data Successfully Written to the file!");
fclose(f);
}
Output
Data Successfully Written to the file!
C Read File:
Reading data from a file is another common feature of file handling. In C, there are various
functions that facilitates different ways and features of reading data from a file, including:
reading all file data at a single go, reading the file data line by line and even to read the file
data character by character.
C Read File functions are:

 C fscanf()
 C fgets()
 C fgetc()
 C fgetw()

❏ C fgetc() function:
To read a single character from a file in C, fgetc() function is used.
Syntax:
fgetc(FILE *stream)
Example 2: Example of fgetc() function.
#include <stdio.h>
void main()
{
FILE *f;
f = fopen("file.txt", "w");
fprintf(f, "Reading data from a file is a common feature of file
handling..\n");
fclose(f);

char ch;
f = fopen("file.txt", "r");
while((ch=fgetc(f))!=EOF)
{
printf("%c",ch);
}
fclose(f);
}
Output
Reading data from a file is a common feature of file handling..

C Fputs() Fgets()
C Write File:
File handling simply means to open a file and to process it according to the required tasks.
Writing data in a file is one of the common feature of file handling. In C, there are various
modes that facilitates different ways and features of writing data into a file, including: w,
r+, w+, a+, wb, rb+, wb+, or ab+ mode. C also supports some functions to write to a file.
C Write File functions are:

 C fprintf()
 C fputs()
 C fputc()
 C fputw()

C fputs() function:
To write a string (line of characters) into a file in C, fputs() function is used.
Syntax:
fputs(const char *s, FILE *stream)
Example 1: Example of fputs() function.
#include <stdio.h>
void main()
{
FILE *f;
f = fopen("file.txt", "w");
fputs("Reading data from a file is a common feature of file
handling..",f);
printf ("Data Successfully Written to the file!");
fclose(f);
}
Output
Data Successfully Written to the file!
C Read File:
Reading data from a file is another common feature of file handling. In C, there are various
functions that facilitates different ways and features of reading data from a file, including:
reading all file data at a single go, reading the file data line by line and even to read the file
data character by character.
C Read File functions are:

 C fscanf()
 C fgets()
 C fgetc()
 C fgetw()

C fgets() function:
To read a string (line of characters) from a file in C, fgets() function is used.
Syntax:
fgets(char *s, int n, FILE *stream)
Example 2: Example of fgets() function.
#include <stdio.h>
void main()
{
FILE *f;
f = fopen("file.txt", "w");
fputs("Reading data from a file is a common feature of file
handling..",f);
fclose(f);

char arr[100];
f = fopen("file.txt","r");
printf("%s",fgets(arr,65,f));
fclose(f);
}
Output
Reading data from a file is a common feature of file handling..

C Fseek()
C fseek() function:
To write data into a file at a desired location, fseek() function is used in C. This function sets
the file pointer in C to a specified offset.
C fseek() function Constants:
Constants used in the fseek() function are:

 SEEK_SET
 SEEK_CUR
 SEEK_END

Syntax:
fseek(FILE *stream, long int offset, int whence)
Example:
#include <stdio.h>
void main(){
FILE *f;

f = fopen("file.txt","w+");
fputs("Hello C..", f);

fseek( f, 6, SEEK_SET );
fputs("World", f);
fclose(f);

char arr[100];
f = fopen("file.txt","r");
printf("%s",fgets(arr,65,f));
fclose(f);
}
Output
Hello World

C Rewind()
C rewind() function:
To use stream many times, the rewind() function is used in C. This function sets the file
pointer at the beginning of the stream.
Syntax:
rewind(FILE *stream)
Example:
#include <stdio.h>
void main(){
FILE *f;

f = fopen("file.txt","w+");
fputs("Hello C..", f);
fclose(f);

char arr[100];
f = fopen("file.txt","r");
printf("%s",fgets(arr,65,f));

rewind(f);
f = fopen("file.txt","r");
printf("%s",fgets(arr,65,f));
fclose(f);
}
Output
Hello C..Hello C..

C Ftell()
C ftell() function:
To get the current file position, ftell() function is used in C.
Syntax:
ftell(FILE *stream)
Example:
#include <stdio.h>
void main(){
FILE *f;

f = fopen("file.txt","w+");
fputs("Hello C..", f);
fclose(f);

f = fopen("file.txt","r");
fseek(f, 0, SEEK_END);

int size = ftell(f);


fclose(f);
printf("Size of file.txt is: %d bytes", size);
}
Output
Size of file.txt is: 9 bytes

C Preprocessor Directives
C Preprocessor Directives:
The Preprocessor Directives are a part of C program which are executed before compilation,
hence the name Preprocessor. These Preprocessor Directives are easily identified as they
starts with hash # symbol. The preprocessors are also used to add macros in a C program.
Some of the Preprocessor Directives are;

 #include
 #define
 #undef
 #ifdef
 #ifndef
 #if
 #else
 #elif
 #endif
 #error
 #pragma

Example:
#include <stdio.h>
void main()
{
printf("Hello C.");
}
Output
Hello C.

C Macros
C Macros:
A macro value in C replaces a part of a program with a value already defined by #define
directive.
Macros can be of four types:
Object-like Macros:
When a macro is simply replaced by a value, then it is called as Object like Macro.
Syntax:
#define macro_Name macro_Value
Function-like Macros:
When a macro is replaced by a logic, same as in a function, then it is called as Function like
Macro.
Syntax:
#define macro_Name macro_Logic
User Defined Macros:
Macros defined in a C program by the user, which are not defined in the C library are called
as user defined Macros.
MACRO USES
_DATE_ To get current date.
_TIME_ To get current time.
_FILE_ To get current file.
_LINE_ To get current line number.
_STDC_ 1
Predefined Macros:
Some macros are already defined in the C library, these macros are called as Predefined
Macros.
Example:
#include<stdio.h>
#define PI 3.14
void main()
{
printf("PI :%f\n",PI );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("STDC :%d\n", __STDC__ );
return 0;
}
Output
PI :3.140000
Date :Sep 19 2018
Time :11:43:00
Line :8
STDC :1

C Preprocessor Include
C# include:
C #include is a preprocessor directive which is used in a C program to include the codes of a
file into the current program file. There are two ways of using #include directive.
#include <file_name>
To check for the directory holding the required system header files, #include <file_name>
is used.
#include “file_name”
To check for the current directory, #include “file_name” is used.
Example:
#include <stdio.h>
void main()
{
printf("Hello C.");
}
Output
Hello C.

C Preprocessor Define
C #define:
A macro value in C replaces a part of a program with a value already defined by #define
directive.
Syntax:
#define macro_Name macro_Value
Example:
#include<stdio.h>
#define PI 3.14
void main()
{
printf("PI :%f\n",PI );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("STDC :%d\n", __STDC__ );
}
Output
PI :3.140000
Date :Sep 19 2018
Time :11:43:00
Line :8
STDC :1

C Preprocessor Undefine
C #undef:
A macro value in C replaces a part of a program with a value already defined by #define
directive. The #undef is a preprocessor directive which is used to undefine the value defined
by #define.
Syntax:
#undef macro_Name
Example:
#include<stdio.h>
#define e 2.718
#undef e
void main()
{
printf("e :%f\n",e );
}
Output
error: 'e' undeclared

C Preprocessor Ifdef
The #ifdef is a preprocessor directive in C which is used to execute a piece of code, only if
the specified macro is already defined by #define.
Syntax:
#ifdef MACRO
// code to be executed if macro is defined
#endif
OR
#ifdef MACRO
// code to be executed if macro is defined
#else
// code to be executed if macro is not defined
#endif
Example:
#include<stdio.h>
#define E 2.718
void main()
{
#ifdef E
printf("E: %f", E);

#else
printf("E is not defined.");

#endif
}
Output
E: 2.718000

C Preprocessor Ifndef
C #ifndef:
The #ifndef is a preprocessor directive in C which is used to execute a piece of code, only if
the specified macro is not defined by #define.
Syntax:
#ifndef MACRO
// code to be executed if macro is not defined
#endif
OR
#ifndef MACRO
// code to be executed if macro is not defined
#else
// code to be executed if macro is defined
#endif
Example:
#include<stdio.h>
#define E 2.718
void main()
{
#ifndef E
printf("E: %f", E);

#else
printf("E is not defined.");

#endif
}
Output
E is not defined.

C Preprocessor If
C #if:
The #if is a preprocessor directive in C which is used to execute a piece of code, only if the
specified condition is TRUE.
Syntax:
#if condition
// code to be executed if condition is TRUE.
#endif
OR
#if condition
// code to be executed if condition is TRUE.
#else
// code to be executed if condition is FALSE.
#endif

Example:
#include<stdio.h>
#define AGE 30
void main()
{
#if (AGE==30)
printf("Value of AGE is correct.");
#else
printf("Wrong value of AGE.");
#endif
}
Output
Value of AGE is correct.

C Preprocessor Else
C #else:
The #else is a preprocessor directive in C which is used with,

 #if to execute a piece of code, only if the specified condition is FALSE.


 #ifdef to execute a piece of code, only if the specified macro is not defined.
 #ifndef to execute a piece of code, only if the specified macro is defined.

Syntax:
#ifdef MACRO
// code to be executed if macro is defined
#else
// code to be executed if macro is not defined
#endif
OR
#ifndef MACRO
// code to be executed if macro is not defined
#else
// code to be executed if macro is defined
#endif
OR
#if condition
// code to be executed if condition is TRUE.
#else
// code to be executed if condition is FALSE.
#endif
Example:
#include<stdio.h>
#define AGE 30
void main()
{
#if (AGE==20)
printf("Value of AGE is correct.");
#else
printf("Wrong value of AGE.");
#endif
}
Output
Wrong value of AGE.

C Preprocessor Error
C #error:
The #error is a preprocessor directive in C which is used to display an error if #error
directive is found during the code execution and thus stops any further compilation of the
code.
Example:
#include<stdio.h>
#ifndef AGE
#error First define then compile
#else
void main()
{
printf("%d",AGE);
}
#endif
Output
error: #error First define then compile

C Preprocessor Pragma
C #pragma:
The #pragma is a preprocessor directive which is used to get additional information related
to machine or operating-system features by the compiler.
Some of the commonly used #pragma directives are:

 #pragma argsused
 #pragma exit
 #pragma hdrfile
 #pragma hdrstop
 #pragma inline
 #pragma option
 #pragma saveregs
 #pragma startup
 #pragma warn

Syntax:
#pragma_directives identifiers
Example:
#include<stdio.h>

void first() ;
#pragma startup first
#pragma exit first

void main()
{
printf("\nBye C.");
}

void first()
{
printf("\nHello C.");
}
Output
Hello C.
Bye C.

C Command Line Arguments


Command line arguments are passed inside the main function of a C program also called as
command line of the C program, hence the name, command line arguments.
Syntax:
data_type main(int argc, char *argv[] )

 Argc: This is a mandatory parameter that counts the number of arguments.


 Argv[]: This is also a mandatory parameter that contains all the arguments.

Example:
#include <stdio.h>
void main(int argc, char *argv[] )
{
printf("File name: %s\n", argv[0]);

if(argc < 2)
{
printf("No argument passed.\n");
}
else
{
printf("Argument 1: %s\n", argv[1]);
}
}
Output
File name: C_program
Argument 1: welcome
1

CORE JAVA CHEATSHEET


Object Oriented Programming Language:​ based on the concepts of “objects”.
Open Source: ​Readily available for development.
Platform-neutral: ​Java code is independent of any particular hardware or software. This is
because Java code is compiled by the compiler and converted into byte code. Byte code is
platform-independent and can run on multiple systems. The only requirement is Java needs a
runtime environment i.e, JRE, which is a set of tools used for developing Java applications.
Memory Management: ​Garbage collected language, i.e. deallocation of memory.
Exception Handling: ​Catches a series of errors or abnormality, thus eliminating any risk of
crashing the system.

THE JAVA BUZZWORDS

Java was modeled in its final form keeping in consideration with the primary objective of having
the following features:

Simple, Small and Familiar

Object-Oriented

Portable and Platform Independent

Compiled and Interpreted

Scalability and Performance

Robust and Secure

Architectural-neutral

High Performance

Multi-Threaded

Distributed

Dynamic and Extensible


2

DATA TYPES IN JAVA

Primitive Data Types

Data Type Default Value Size (in bytes)


1 byte = 8 bits

boolean FALSE 1 bit

char “ “ (space) 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Non-Primitive Data Types

Data Type

String

Array

Class

Interface

​TYPECASTING

It is a method of converting a variable of one data type to another data type so that functions
can process these variables correctly.
Java defines two types of typecasting:
● Implicit Type Casting (Widening)
3

Storing a variable of a smaller data type to a larger data type.


● Explicit Typecasting (Narrowing)
Storing variable of a larger data type to a smaller data type.

OPERATORS IN JAVA

Java supports a rich set of operators that can be classified into categories as below :

Operator Category Operators

Arithmetic operators +,-,/,*,%

Relational operators <, >, <=, >=,==, !=

Logical operators && , ||

Assignment operator =, +=, −=, ×=, ÷=, %=, &=, ^=, |=, <<=, >>=, >>>=

Increment and Decrement operator ++ , - -

Conditional operators ?:

Bitwise operators ^, &, |

Special operators . (dot operator to access methods of class)

JAVA IDE and EXECUTING CODE

Amongst many IDEs the most recommended ones are :


● Eclipse
● NetBeans

Java code can also be written in any text editor and compiled on the terminal with following
commands :

$ java [file_name].java

$ java [file_name]

Note​: File name should be the same as the class name containing the main() method, with a
.java extension.

VARIABLES IN JAVA

Variables are the name of the memory location. It is a container that holds the value while the
java program is executed. Variables are of three types in Java :
4

Local Variable Global or Instance Variable Static Variable

Declared and initialized inside Declared inside the class but Declared using a “static”
the body of the method, block or outside of the method, block or keyword. It cannot be local.
constructor. constructor. If not initialized, the
default value is 0.

It has an access only within the Variables are created when an Variables created creates a
method in which it is declared instance of the class is created single copy in the memory which
and is destroyed later from the and destroyed when it is is shared among all objects at a
block or when the function call is destroyed. class level.
returned.

class TestVariables

int data = 20; // instance variable

static int number = 10; //static variable

void someMethod()

int num = 30; //local variable

RESERVED WORDS

Also known as keywords, are particular words which are predefined in Java and cannot be used
as variable or object name. Some of the important keywords are :
5

Keywords Usage

abstract used to declare an abstract class.

catch used to catch exceptions generated by try statements.

class used to declare a class.

enum defines a set of constants

extends indicates that class is inherited

final indicates the value cannot be changed

finally used to execute code after the try-catch structure.

implements used to implement an interface.

new used to create new objects.

static used to indicate that a variable or a method is a class method.

super used to refer to the parent class.

this used to refer to the current object in a method or constructor.

throw used to explicitly throw an exception.

throws used to declare an exception.

try block of code to handle exception

METHODS IN JAVA

The general form of method :

type name (parameter list)


{
//body of the method

//return value (only if type is not void)


}

Where type - return type of the method


name - name of the method
parameter list - sequence of type and variables separated by a comma
return - statement to return value to calling routine
6

CONDITIONAL STATEMENTS IN JAVA

1. if-else

Tests condition, if condition true if block is executed else the else block is executed.

class TestIfElse
{
public static void main(String args[])
{
int percent = 75;

if(percent >= 75)


{
System.out.println("Passed");
}
else
{
System.out.println("Please attempt again!");
}
}

2. Switch

Test the condition, if a particular case is true the control is passed to that block and executed.
The rest of the cases are not considered further and the program breaks out of the loop.

class TestSwitch
{
public static void main(String args[])
{
int weather = 0;

switch(weather)
{
case 0 :
System.out.println("Sunny");
7

break;
case 1 :
System.out.println("Rainy");
break;
case 2 :
System.out.println("Cold");
break;
case 3 :
System.out.println("Windy");
break;
default :
System.out.println("Pleasant");
}
}
}

LOOPS IN JAVA

Loops are used to iterate the code a specific number of times until the specified condition is
true. There are three kinds of loop in Java :

For Loop

Iterates the code for a specific number of times until class TestForLoop
the condition is true. {
public static void main (String args[])
{
for(int i=0;i<=5;i++)

System.out.println("*");
}
}

While Loop

If condition in the while is true the program enters the class TestWhileLoop
loop for iteration. {
public static void main (String args[])
{
int i = 1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}

Do While Loop
8

The program enters the loop for iteration at least once class TestDoWhileLoop
irrespective of the while condition being true. For {
further iterations, it is depends on the while condition public static void main (String args[])
to be true. {
int i = 1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}

JAVA OOPS CONCEPTS

An object-oriented paradigm offers the following concepts to simplify software development and
maintenance.

1. Object and Class

Objects are basic runtime entities in an object-oriented system, which contain data and code to
manipulate data. This entire set of data and code can be made into user-defined data type using
the concept of class. Hence, a class is a collection of objects of a similar data type.
Example: apple, mango, and orange are members of class fruit.

2. Data Abstraction and Encapsulation

The wrapping or enclosing up of data and methods into a single unit is known as encapsulation.
Take medicinal capsule as an example, we don’t know what chemical it contains, we are only
concerned with its effect.

This insulation of data from direct access by the program is called data hiding. For instance,
while using apps people are concerned about its functionality and not the code behind it.

3.Inheritance

Inheritance provides the concept of reusability, it is the process by which objects of one class
(Child class or Subclass) inherit or derive properties of objects of another class (Parent class).

Types of Inheritance in Java:

Single Inheritance
9

The child class inherits properties and behavior from a single parent class.

Multilevel Inheritance

The child class inherits properties from its parent class, which in turn is a child class to another parent class

Multiple Inheritance

When a child class has two parent classes. In Java, this concept is achieved by using interfaces.

Hierarchical Inheritance

When a parent class has two child classes inheriting its properties.

class A
{
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}

class SimpleInheritance {
public static void main(String args[]) {
A objA = new A();
B objB = new B();
// The superclass may be used by itself.
objA.i = 10;
objA.j = 20;
System.out.println("Contents of objA: ");
objA.showij();
System.out.println();
/* The subclass can access to all public members of
its superclass. */
objB.i = 7;
objB.j = 8;
objB.k = 9;
10

System.out.println("Contents of objB: ");


objB.showij();
objB.showk();
System.out.println();
System.out.println("Sum of i, j and k in objB:");
objB.sum();
}
}

Some limitations in Inheritance :


● Private members of the superclass cannot be derived by the subclass.
● Constructors cannot be inherited by the subclass.
● There can be one superclass to a subclass.

4. Polymorphism

Defined as the ability to take more than one form. Polymorphism allows creating clean and
readable code.
In Java Polymorphism is achieved by the concept of method overloading and method
overriding, which is the dynamic approach.

● Method Overriding

In a class hierarchy, when a method in a child class has the same name and type signature as a
method in its parent class, then the method in the child class is said to override the method in
the parent class.

In the code below, if we don’t override the method the output would be 4 as calculated in
ParentMath class, otherwise, it would be 16.

class ParentMath
{
void area()
{
int a =2;
System.out.printf("Area of Square with side 2 = %d %n", a * a);
System.out.println();
}
}

class ChildMath extends ParentMath


{
11

void area()
{
int a =4;
System.out.printf("Area of Square with side 4= %d %n", a * a);
}

public static void main (String args[])


{
ChildMath obj = new ChildMath();
obj.area();
}
}

● Method Overloading

Java programming can have two or more methods in the same class sharing the same name,
as long as their arguments declarations are different. Such methods are referred to as
overloaded, and the process is called method overloading.

Three ways to overload a method :

1. Number of parameters
example: add(int, int)
add(int, int, int)

2. Data type of parameters


example add(int, int)
add(int, float)

3.Sequence of data type of parameters


example add(int, float)
add(float, int)

Program to explain multilevel inheritance and method overloading :

class Shape
{
void area()
{
System.out.println("Area of the following shapes are : ");
}
}
12

class Square extends Shape


{

void area(int length)


{
//calculate area of square
int area = length * length;
System.out.println("Area of square : "+area);
}
}

class Rectangle extends Shape


{
//define a breadth

void area(int length,int breadth)


{
//calculate area of rectangle
int area = length * breadth;
System.out.println("Area of rectangle : " + area);
}
}

class Circle extends Shape


{
void area(int breadth)
{
//calculate area of circle using length of the shape class as radius
float area = 3.14f * breadth * breadth;
System.out.println("Area of circle : " + area);
}
}

class InheritanceOverload
{
public static void main(String[] args)
{
int length = 5;
int breadth = 7;
Shape s = new Shape();
//object of child class square
Square sq = new Square();
//object of child class rectangle
13

Rectangle rec = new Rectangle();


//object of child class circle
Circle cir = new Circle();

//calling the area methods of all child classes to get the area of different objects
s.area();
sq.area(length);
rec.area(length,breadth);
cir.area(length);
}
}

ABSTRACT CLASS

Superclass that only defines a generalized form that will be shared by all of its subclasses,
leaving it to each subclass to implement its methods.

abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}

class Abstract {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}

INTERFACES
14

A class’s interface can be full abstracted from its implementation using the “interface” keyword.
They are similar to class except that they lack instance variables and their methods are
declared without any body.

● Several classes can implement an interface.


● Interfaces are used to implement multiple inheritances.
● Variables are public, final and static.
● To implement an interface, a class must create a complete set of methods as defined by
an interface.
● Classes implementing interfaces can define methods of their own.

interface Area
{
final static float pi = 3.14F;
float compute(float x , float y);
}

class Rectangle implements Area


{
public float compute (float x, float y)
{
return (x*y);
}
}

class Circle implements Area


{
public float compute (float x, float y)
{
return (pi * x * x);
}
}

class InterfaceTest
{
public static void main (String args[])
{
float x = 2.0F;
float y = 6.0F;
Rectangle rect = new Rectangle(); //creating object
Circle cir = new Circle();

float result1 = rect.compute(x,y);


15

System.out.println("Area of Rectangle = "+ result1);

float result2 = cir.compute(x,y);


System.out.println("Area of Circle = "+ result2);
}
}

CONSTRUCTORS IN JAVA

● A constructor initializes an object on creation.


● They have the same name as the class.
● They do not have any return type, not even void.
● Constructor cannot be static, abstract or final.
● Constructors can be :
● Non - Parameterized or Default Constructor: Invoked automatically even if not declared

class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

class BoxVol {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

vol = mybox1.volume();
System.out.println("Volume is " + vol);
16

vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Parameterized :

Used to initialize the fields of the class with predefined values from the user.

class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

double volume() {
return width * height * depth;
}
}
class BoxVolP {
public static void main(String args[]) {

Box mybox1 = new Box(10, 20, 15);


Box mybox2 = new Box(3, 6, 9);
double vol;

vol = mybox1.volume();
System.out.println("Volume is " + vol);

vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

ARRAYS IN JAVA
17

Array is a group of like-type variables that are referred by a common name, having continuous
memory. Primitive values or objects can be stored in an array. It provides code optimization
since we can sort data efficiently and also access it randomly. The only flaw is that we can have
a fixed-size elements in an array.

There are two kinds of arrays defined in Java:

1. Single Dimensional: Elements are stored in a single row

import java.util.Scanner;

class SingleArray
{
public static void main(String args[])
{
int len = 0;
//declaration
int [] numbers = {3,44,12,53,6,87};
Scanner s = new Scanner(System.in);

System.out.println("The elements in the array are: ");


for(int i=0;i<numbers.length;i++)
{
System.out.print(numbers[i] + " ");
}
System.out.println();

System.out.println("The sum of elements in the array are: ");


int sum =0;
for(int i=0;i<numbers.length;i++)
{
sum = sum + numbers[i];
}
System.out.println("Sum of elements = " + sum);
}
}

2. Multi-Dimensional: Elements are stored as row and column

class MatrixArray
18

public static void main(String args[])

int [][] m1 = { {1,5,7}, {2,4,6}};

int [][] m2 = {{1,2,1},{4,4,3}};

int [][] sum = new int [3][3];

//printing matrix

System.out.println("The given matrix is : ");

for(int a=0;a<=m1.length;a++)

for(int b=0;b<=m2.length;b++)

System.out.print(m1[a][b] + " ");

System.out.println();

//matrix addition

System.out.println("The sum of given 2 matrices is : ");


19

for(int a=0;a<=m1.length;a++)

for(int b=0;b<=m2.length;b++)

sum[a][b] = m1[a][b] + m2[a][b];

System.out.print(sum[a][b] + " ");

System.out.println();

STRINGS IN JAVA

● Strings are non-primitive data type that represents a sequence of characters.


● String type is used to declare string variables.
● Array of strings can also be declared.
● Java strings are immutable, we cannot change them.
● Whenever a string variable is created, a new instance is created.

Creating String

Using Literal Using new keyword

String name = “John” ; String s = new String();

String Methods

The String class which implements CharSequence interface defines a number of methods for
string manipulation tasks. List of most commonly used string methods are mentioned below:
20

Method Task Performed

toLowerCase() converts the string to lower case

toUpperCase() converts the string to upper case

replace(‘x’ , ‘y’) replaces all appearances of ‘x’ with ‘y’

trim() removes the whitespaces at the beginning and at the end

equals() returns ‘true’ if strings are equal

equalsIgnoreCase() returns ‘true’ if strings are equal, irrespective of case of


characters

length() returns the length of string

CharAt(n) gives the nth character of string

compareTo() returns negative if string 1 < string 2


positive if string 1 > string 2
zero if string 1 = string 2

concat() concatenates two strings

substring(n) returns substring returning from character n

substring(n,m) returns a substring between n and ma character.

toString() creates the string representation of object

indexOf(‘x’) returns the position of first occurrence of x in the string.

indexOf(‘x’,n) returns the position of after nth position in string

ValueOf (Variable) converts the parameter value to string representation

Program to show Sorting of Strings:

class SortStrings {
static String arr[] = {
"Now", "the", "is", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "county"
};
public static void main(String args[])
{
for(int j = 0; j < arr.length; j++)
{
for(int i = j + 1; i < arr.length; i++)
{
if(arr[i].compareTo(arr[j]) < 0)
{
String t = arr[j];
arr[j] = arr[i];
21

arr[i] = t;
}
}
System.out.println(arr[j]);
} }
}

String Buffer and String Builder

● For mutable strings, we can use StringBuilder and StringBuffer classes which as well
implement CharSequence interface.
● These classes represent growable and writable character interface.
● They automatically grow to make room for additions , and often has more characters
preallocated than are actually needed, to allow room for growth.

Difference between length() and capacity()

length() : To find the length of StringBuffer


capacity() : To find the total allocated capacity

/* StringBuffer length vs. capacity */


class StringBufferTest {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
StringBuilder versus StringBuffer

String Builder String Buffer

Non-Synchronized : hence efficient. Synchronized

Threads are used, multithreading. Thread Safe

MULTITHREADING

Multitasking: ​Process of executing multiple tasks simultaneously, to utilize the CPU.

This can be achieved in two-ways:


22

● Process-based multitasking.(Multitasking)
● Thread-based multitasking (Multithreading)

Multitasking versus Multithreading

Multitasking Multithreading

OS concept in which multiple tasks are performed Concept of dividing a process into two or more
simultaneously. subprocess or threads that are executed at the
same time in parallel.

Multiple programs can be executed Supports the execution of multiple parts of a


simultaneously. single program simultaneously.

Process has to switch between different programs Processor needs to switch between different
or processes. parts or threads of the program.

less efficient highly efficient

program or process in the smallest unit in the thread is the smallest unit
environment

cost effective expensive

Life Cycle Of Thread

A thread is always in one of the following five states, it can move from state to another by a
variety of ways as shown.

New thread:​ Thread object is created. Either it can be scheduled for running using start()
method.
Runnable thread :​ Thread is ready for execution and waiting for processor.
Running thread: ​It has got the processor for execution.
Blocked thread: ​ Thread is prevented from entering into runnable state.
Dead state: ​Running thread ends its life when it has completed executing its run() method.
23

Creating Thread

Extending Thread class


Implementing Runnable interface

Common Methods Of Thread Class

Method Task Performed

public void run() Inherited by class MyThread


It is called when thread is started, thus all the action takes place in
run()

public void start() Causes the thread to move to runnable state.

public void sleep(long Blocks or suspends a thread temporarily for entering into
milliseconds) runnable and subsequently in running state for specified
milliseconds.

public void yield Temporarily pauses currently executing thread object and allows
other threads to be executed.

public void suspend() to suspend the thread, used with resume() method.

public void resume() to resume the suspended thread

public void stop() to cause premature death of thread, thus moving it to dead state.

Program to create threads using thread class.


24

class A extends Thread


{
public void run()

{
for(int i=1;i<=5;i++)
{
System.out.println("From thread A : i " + i);
}
System.out.println("Exit from A ");
}
}

class B extends Thread


{
public void run()

{
for(int i=0;i<=5;i++)
{
System.out.println("From thread B : i " + i);
}
System.out.println("Exit from B ");
}
}

class C extends Thread


{
public void run ()
{
for(int k=1;k<=5;k++)
{
System.out.println("From thread C : k " + k);
}
System.out.println("Exit from C ");
}
}

class ThreadTest
{
public static void main(String args[])
{
25

new A().start();
new B().start();
new C().start();
}
}

Implementing Runnable Interface

The run( ) method that is declared in the Runnable interface which is required for implementing
threads in our programs.

Process consists of following steps :


● Class declaration implementing the Runnable interface
● Implementing the run() method
● Creating a thread by defining an object that is instantiated from this “runnable” class as
the target of the thread.
● Calling the thread’s start() method to run the thread.

Using Runnable Interface

class X implements Runnable


{
public void run()
{
for(int i=0;i<=10;i++)
{
System.out.println("Thread X " + i);
}
System.out.println("End of thread X ");
}
}

class RunnableTest
{
public static void main(String args[])
{
X runnable = new X ();
Thread threadX = new Thread(runnable);
threadX.start();
System.out.println("End of main Thread");
}
}
26

Thread Class Versus Runnable Interface

Thread Class Runnable Interface

Derived class extending Thread class itself is a Runnable Interface simply defines the unit of work
thread object and hence, gains full control over that will be executed in a thread, so it doesn’t
the thread life cycle. provide any control over thread life cycle.

The derived class cannot extend other base Allows to extend base classes if necessary
classes

Used when program needs control over thread life Used when program needs flexibility of extending
cycle classes.

EXCEPTION HANDLING

Exception is an abnormality or error condition that is caused by a run-time error in the program,
if this exception object thrown by error condition is not caught and handled properly, the
interpreter will display an error message. If we want to avoid this and want the program to
continue then we should try to catch the exceptions.This task is known as exception handling.

Common Java Exceptions

Exception Type Cause of Exception

ArithmeticException caused by math errors

ArrayIndexOutOfBoundException caused by bad array indexes

ArrayStoreException caused when a program tries to store wrong data type in an


array

FileNotFoundException caused by attempt to access a nonexistent file

IOException caused by general I/O failures.

NullPointerException caused by referencing a null object.

NumberFormatException caused when a conversion between strings and number fails.

OutOfMemoryException caused when there is not enough memory to allocate

StringIndexOutOfBoundException caused when a program attempts to access a non-existent


character position in a string.

Exceptions in java can be of two types:

Checked Exceptions :
● Handled explicitly in the code itself with the help of try catch block.
● Extended from java.lang.Exception class
Unchecked Exceptions :
27

● Not essentially handled in the program code, instead JVM handles such exceptions.
● Extended from java.lang.RuntimeException class

TRY AND CATCH

Try keyword is used to preface a block of code that is likely to cause an error condition and
“throw” an exception. A catch block defined by the keyword catch “catches” the exception
“thrown” by the try block and handles it appropriately.

A code can have more than one catch statement in the catch block, when exception in try block
is generated, multiple catch statements are treated like cases in a switch statement.

Using Try and Catch for Exception Handling

class Error
{
public static void main(String args[])
{
int a [] = {5,10};
int b = 5;

try
{
int x = a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexError");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}

int y = a[1]/a[0];
System.out.println("y = " + y);
}
}
28

FINALLY

Finally statement: ​used to handle exceptions that is not caught by any of the previous catch
statements. A finally block in guaranteed to execute, regardless of whether or not an exception
is thrown.

We can edit the above program and add the following finally block.

finally
{
int y = a[1]/a[0];
System.out.println("y = " + y);
}

THROWING YOUR OWN EXCEPTION

Own exceptions can be defined using throw keyword.

throw new Throwable subclass;

/* Throwing our own Exception */

import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}

class TestMyException
{
public static void main(String args[])
{
int x = 5 , y = 1000;
try
{
float z = (float) x / (float) y ;
if(z < 0.01)
{
throw new MyException("Number is too small");
29

}
}
catch (MyException e)
{
System.out.println("Caught my exception ");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am always here");
}
}
}
MANAGING FILES IN JAVA

Storing data in variables and arrays poses the following problems:

● Temporary Storage:​ The data is lost when variable goes out of scope or when program
is terminates.
● Large data:​ It is difficult

Such problems can be solved by storing data on secondary devices using the concept of files.
Collection of related records stored in a particular area on the disk, termed as file. The files
store and manage data by the concept of file handling.

Files processing includes:

● Creating files
● Updating files
● Manipulation of data

Java provides many features in file management like :


● Reading/writing of data can be done at the byte level or at character or fields depending
upon the requirement.
● It also provides capability read/write objects directly.

STREAMS

Java uses concept of streams to represent ordered sequence of data, which is a path along
which data flows. It has a source and a destination.

Streams are classified into two basic types :


30

● Input Stream: ​which extracts i.e. reads data from source file and sends it to the
program.
● Output Stream:​ which takes the data from the program and send i.e writes to the
destination.

STREAM CLASSES

They are contained in​ ​java.lang.io​ package.

They are categorized into two groups


1.​ Byte Stream Classes:​ provides support for handling I/O operation on bytes.
2. ​Character Stream Classes: ​provides support for managing I/O operations on
characters.

BYTE STREAM CLASSES

Designed to provide functionality for creating and manipulating streams and files for
reading/writing bytes.

Since streams are unidirectional there are two kinds of byte stream classes :

● Input Stream Classes


● Output Stream Classes

INPUT STREAM CLASSES

They are used to read 8-bit bytes include a super class known as InputStream. InputStream is
an abstract class and defines the methods for input functions such as :

Method Description

read( ) Reads a byte from input stream

read(byte b [ ]) Reads an array of bytes into b

read(byte b [ ], int n, int m) Reads m bytes into b starting from the nth byte of b

available( ) Tells number of bytes available in the input

skip(n) Skips over n bytes from the input stream

reset ( ) Goes back to the beginning of the stream

close ( ) Closes the input stream

OUTPUT STREAM CLASSES


31

These classes are derived from the base class OutputStream. OutputStream is an abstract
class and defines the methods for output functions such as :

Method Description

write( ) Writes a byte to the output stream

write(byte b[ ]) Writes all the bytes in the array b to the output stream

write(byte b[ ], int n, int m) Writes m bytes from array b starting from the nth byte

close( ) Closes the output stream

flush( ) Flushes the output stream

READING/WRITING BYTES

Two common subclasses used are FileInputStream and FileOutputStream that handle 8-bit
bytes.
FileOutputStream is used for writing bytes to a file as demonstrated below:

// Writing bytes to a file

import java.io.*;

class WriteBytes
{
public static void main(String args[])
{
bytes cities [] = {'C','A','L','I','F','O','R','N','I','A', '\n',
'V','E','G','A','S','\n','R','E','N','O','\n'};

//Create output file stream


FileOutputStream outfile = null;
try
{
//connect the outfile stream to "city.txt"
outfile = new FileOutputStream("city.txt");
//Write data to the stream
outfile.write(cities);
outfile.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
32

System.exit(-1);
}
}
}

FileIntputStream is used for reading bytes from a file as demonstrated below:

//Reading bytes from a file

import java.io.*;

class ReadBytes
{
public static void main(String args[])
{
//Create an input file stream
FileInputStream infile = null;
int b;
try
{
//connect the infile stream to required file
infile = new FileInputStream(args [ 0 ]);

//Read and display


while( (b = infile.read ( ) ) !=-1)
{
System.out.print((char) b );
}
infile.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
System.exit(-1);
}
}
}

CHARACTER STREAM CLASSES

Two kinds of character stream classes :

Reader Stream Classes


33

● Designed to read character from the files.


● Class Reader is the base class for all other classes.
● These classes are similar to input stream classes except their fundamental unit of
information, while reader stream uses characters.

Writer Stream Classes

● Performs all output operations on files.


● Writes characters
● The Writer class is an abstract class which is the base class, having methods identical to
those of OutputStream.

READING/WRITING CHARACTERS

The two subclasses of Reader and Writer classes for handling characters in files are FileReader
and FileWriter.

// Copying characters from one file to another

import java.io.*;

class CopyCharacters
{
public static void main (String args[])
{
//Declare and create input and output files
File inFile = new File("input.dat");
File outFile = new File("output.dat");
FileReader ins = null; //creates file stream
ins
FileWriter outs = null; //creates file stream
outs

try
{
ins = new FileReader(inFile); //opens inFile
outs = new FileWriter(outFile); //opens outFile

//Read and write


int ch;
while((ch = ins.read( ))!=-1)
{
34

outs.write(ch);
}
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{
ins.close();
outs.close();
}
catch (IOException e)
{}
}
}
}

JAVA COLLECTIONS

The collections framework contained in the java.util package defines a set of interfaces and their
implementations to manipulate collections, which serve as a container for a group of objects.

INTERFACES

Collection framework contains many interfaces such as Collection, Map and Iterator.
The interfaces and their description are mentioned below:

Interface Description

Collection collection of elements

List (extends Collection) sequence of elements

Queue (extends Collection) special type of list

Set (extends Collection) collection of unique elements

SortedSet (extends Set) sorted collection of unique elements

Map collection of key and value pairs, which must be unique


35

SortedMap (extends Map) sorted collection of key value pairs

Iterator object used to traverse through a collection

List (extends Iterator) object used to traverse through a sequence

CLASSES

The classes available in the collection framework implement the collection interface and
sub-interfaces. They also implement Map and Iterator interfaces.

Classes and their Corresponding interfaces are listed :

Class Interface

AbstractCollection Collection

AbstarctList List

Abstract Queue

AbstractSequentialList List

LinkedList List

ArrayList List, Cloneable and Serializable

AbstractSet Set

EnumSet Set

HashSet Set

PriorityQueue Queue

TreeSet Set

Vector List, Cloneable and Serializable

Stack List, Cloneable and Serializable

Hashtable Map, Cloneable and Serializable

Array List Implementation

// Using the methods of array list class

import java.util.*;
class Num
{
public static void main(String args[])
{
ArrayList num = new ArrayList ();
num.add(9);
36

num.add(12);
num.add(10);
num.add(16);
num.add(6);
num.add(8);
num.add(56);

//printing array list


System.out.println("Elements : ");
num.forEach((s) -> System.out.println(s));

//getting size
System.out.println("Size of array list is: ");
num.size();

//retrieving specific element


int n = (Integer) num.get(2);
System.out.println(n);

//removing an element
num.remove(4);

//printing array list


System.out.println("Elements : ");
num.forEach((s) -> System.out.println(s));
}
}

Linked List Implementation

import java.util.Scanner;
class LinkedList
{
public static void main (String args[])
{
Scanner s = new Scanner(System.in);
List list = new List();
System.out.println("Enter the number of elements you want to enter in LL
: ");
int num_elements = s.nextInt();
37

int x;
for(int i =0;i<=num_elements;i++)
{
System.out.println("Enter element : ");
x = s.nextInt();
list.insert(x);
}
System.out.println(">>>>> LINKED LIST AFTER INSERTION IS : ");
list.print();
int size = list.count();
System.out.println(">>>>> SIZE OF LL => "+size);
System.out.println("Enter the node to be inserted in the middle: ");
int mid_element = s.nextInt();
list.insertMiddle(mid_element);
System.out.println(">>>> LL AFTER INSERTING THE NEW ELEMENT
IN THE MIDDLE ");
list.print();
}
}

HashSet Implementation

import java.util.*;
class HashSetExample
{
public static void main(String args[])
{
HashSet hs = new HashSet();
hs.add("D");
hs.add("W");
hs.add("G");
hs.add("L");
hs.add("Y");
System.out.println("The elements available in the hash set are :" + hs);
}
}

Tree Set Implementation

import java.util.*;
class TreeSetExample
{
public static void main(String args[])
38

{
TreeSet ts = new TreeSet();
ts.add("D");
ts.add("W");
ts.add("G");
ts.add("L");
ts.add("Y");
System.out.println("The elements available in the hash set are :" + ts);
}
}

Vector Class Implementation

import java.util.*;
class VectorExample
{
public static void main(String args[])
{
Vector fruits = new Vector ();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Grapes");
fruits.add("Pineapple");
Iterator it = fruits.iterator();
while (it.hasNext())
{
System.out.println(it.next);
}
}
}

Stack Class Implementation

import java.util.*;

public class StackExample


{
public static void main (String args[])
{
Stack st = new Stack ();
st.push("Java");
st.push("Classes");
39

st.push("Objects");
st.push("Multithreading");
st.push("Programming");

System.out.println("The elements in the Stack : " + st);


System.out.println("The elements at the top of Stack : " + st.peek());
System.out.println("The elements popped out of the Stack : " + st.pop());
System.out.println("The elements in the Stack after pop of the element : "
+ st);
System.out.println("The result of search : " + st.search ("r e"));
}
}

HashTable Class Implementation

import java.util.*;

public class HashTableExample


{
public static void main (String args[])
{
Hashtable ht = new Hashtable();
ht.put("Item 1","Apple");
ht.put("Item 2","Orange");
ht.put("Item 3","Grapes");
ht.put("Item 4","Pine");
ht.put("Item 5","Kiwi");

Enumeration e = ht.keys();
while(e.hasMoreElements())
{
String str = (String) e.nextElement();
System.out.println(ht.get(str));
}
}
}

MEMORY MANAGEMENT IN JAVA

Memory is a collection of data represented in the binary format.

Memory management is :
40

● Process of allocating new objects


● Properly removing unused objects( garbage collection)

Example Illustrating Memory Management


41

1. When a method is called , frame is created on the top of the stack.


2. Once a method as completed execution, the flow of control returns to the calling method
and its corresponding stack frame is flushed.
3. Local variables are created in stack.
4. Instance variables are created in the heap and are part of the object they belong to.
5. Reference variable are created in stack.

SOME COMMON JAVA CODING QUESTIONS

1. Enter radius and print diameter, perimeter and area

import java.util.Scanner;

class Circle
{
public static void main (String args [])
{
double r,dia,peri,area ;
System.out.println("Enter the radius of circle : ");
42

Scanner s = new Scanner (System.in);


r = s.nextDouble();

dia = 2*r;
peri = 2*Math.PI*r;
area = Math.PI*r*r;

System.out.printf("The dia of circle is : %.2f \n", dia);


System.out.printf("The peri of circle is : %.2f \n", peri);
System.out.printf("The area of the circle is : %.2f \n", area);
}
}

2. Print all the even numbers between x and y.

import java.util.Scanner;
class EvenOdd
{
public static void main (String args[])
{
int x,y;
Scanner s = new Scanner (System.in);
System.out.println("Enter the values x , y : ");
x = s.nextInt();
y = s.nextInt();

System.out.println(" **** EVEN NUMBERS BETWEEN GIVEN RANGE


ARE **** >> ");
int count = x;
while(count <=y)
{
if(count % 2 == 0)
{
System.out.println(count);
}
count ++;
}
}
}

3. To check if given number is prime


43

import java.util.Scanner;

class Prime
{
public static void main (String args[])
{
double num;
int n;
boolean isPrime = true;
Scanner s = new Scanner(System.in);

System.out.println("Enter the number to check :");


num=s.nextDouble();

n = (int) Math.sqrt(num);

for(int i=2;i<=n;i++)
{
if(num % i == 0)
{
isPrime = false;
}
else
{
isPrime = true;
}
}

if(isPrime)
{
System.out.println("***** NUMBER IS PRIME !!!! ****** ");
}
else
{
System.out.println("***** NUMBER IS NOT PRIME !!!! ****** ");

}
}
}

4. To check if the entered number is Palindrome


44

import java.util.Scanner;

class Palindrome
{
public static void main(String args[])
{
int num,reverse=0,mode;
Scanner s = new Scanner(System.in);

System.out.println("Enter a number to check for Palindrome: ");


num = s.nextInt();

int number = num;


while(num!=0)
{
//System.out.println(" number entering = "+num);
mode = num % 10;
//System.out.println(" mode = "+mode);
reverse =(reverse * 10 )+ mode;
//System.out.println(" reverse = "+reverse);
num = num/10;
//System.out.println(" new num = "+num);
}

//System.out.println(" reverse out = "+reverse);

if(reverse == number)
{
System.out.println(" **** PALINDROME !!! **** ");
}
else
{
System.out.println(" **** NOT A PALINDROME !!! **** ");
}
}
}

5. Pattern printing

*
**
45

***
****
*****

import java.util.Scanner;

class TriStars
{
public static void main(String args[])
{
for(int i=0;i<=5;i++)
{
for(int j=0;j<i;j++)
{
System.out.print(" * ");
}
System.out.println();
}
System.out.println();
}
}
SQL
SQL tutorial for beginners and professionals with examples on Basics, Structured,
Programming, Language, Syntax, Database, Clauses, database concepts, SQL Syntax,
SELECT, INSERT, DELETE, UPDATE, DROP, TRUNCATE, DISTINCT, ORDER BY, GROUP BY,
WHERE and more.
A database is an organized collection of data.

DBMS:
DBMS refers to the Database Management System. It is a set of programs that enables you
to store, modify, and retrieve the data from a database.

RDBMS:
RDBMS refers to the Relational Database Management System. It is a database
management system that is based on the relational model as introduced by E. F. Codd. All
modern database systems like MS SQL Server, Oracle, IBM DB2, MySQL, and Microsoft
Access are based on RDBMS.

Difference between DBMS and RDBMS:


DBMS RDBMS
1. RDBMS define the integrity
1. DBMS does not define any constraints or
constraint to ensure the ACID
security to ensure the ACID PROPERTY.
PROPERTY.
2. Normalization concept is not present.
2. Normalization concept is present.
3. In DBMS data is treated as files
3. In RDBMS data is treated as tables
internally.
internally.
4. DBMS does not support distributed
4. RDBMS support distributed
databases.
databases.
5. DBMS supports single user.
5. RDBMS supports multiple users.

SQL stands for Structured Query Language. SQL is a computer language for accessing
databases. It is used to store, manipulate and retrieve the data stored in a database.

SQL Commands:
SQL Commands are the instructions which are used to interact with the database to perform
a specific task.

SQL Commands categories:


1. DDL (Data Definition Language):
DDL commands are used to define the structure of database objects.
1. CREATE – It is used to create database objects like table, view etc.
2. ALTER – It is used to alter the structure of the existing database object.
3. DROP – It is used to delete the existing objects from the database.
4. TRUNCATE – It remove all records from a table, including all spaces allocated for the
records will be removed.
5. RENAME – It is used to rename an existing database object.

2. DML (Data Manipulation Language):


1. SELECT – It is used to retrieve the records from the database.
2. INSERT – It is used to create a record.
3. UPDATE – It is used to modify an existing record.
4. DELETE – It is used to delete all records from a table, the space for the records remain.
5. MERGE- It is used to insert or update a record.
6. CALL – call a PL/SQL or Java subprogram.
7. LOCK TABLE – It is used to control concurrency.

3. DCL (Data Control Language):


1. GRANT – It gives privileges to user.
2. REVOKE – It withdraw access privileges from a user given with the GRANT command.

4. TCL (Transaction Control):


1. COMMIT – It is used to save the work done.
2. SAVEPOINT – It is used to identify a point in a transaction to which you can roll back
later.
3. ROLLBACK – It is used to restore the database to original since the last COMMIT.

SQL Syntax
Syntax:
Syntax is a set of rules and guidelines which defines the structure of statements in a
computer language.

SQL syntax:
SQL syntax is a set of rules and guidelines which defines the structure of SQL statements.
SQL is case insensitive.

Commonly used SQL commands:


1. SELECT – It is used to extract data from a database.
2. UPDATE – It is used to update data in a database.
3. DELETE – It is used to delete data from a database.
4. INSERT INTO – It is used to insert new data into a database.
5. CREATE DATABASE – It is used to create a new database.
6. ALTER DATABASE – It is used to modify an existing database.
7. CREATE TABLE – It is used to create a new table.
8. ALTER TABLE – It is used to modify an existing table.
9. DROP TABLE – It is used to delete an existing table.
10. CREATE INDEX – It is used to create an index (search key).
11. DROP INDEX – It is used to delete an existing index.

SQL Data Type


SQL data type defines the type and range of the data that can be used with SQL Server.

Commonly used SQL data types:


Data Type Syntax Description
integer integer Integer number.
smallint smallint Small integer number.
numeric numeric(p,s) Where p is a precision value; s is a scale value. For
example, numeric(7,3) is a number that has 4 digits
before the decimal and 3 digits after the decimal.
decimal decimal(p,s) Where p is a precision value; s is a scale value.
real real Single-precision floating point number
double
double precision Double-precision floating point number
precision
float float(p) Where p is a precision value.
Where x is the number of characters to store. This data
character char(x) type is space padded to fill the number of characters
specified.
character Where x is the number of characters to store. This data
varchar2(x)
varying type does NOT space pad.
bit bit(x) Where x is the number of bits to store.
Where x is the number of bits to store. The length can
bit varying bit varying(x)
vary up to x.
date date Stores year, month, and day values.
time time Stores the hour, minute, and second values.
Stores year, month, day, hour, minute, and second
timestamp timestamp
values.
time with time time with time Exactly the same as time, but also stores an offset from
zone zone UTC of the time specified.
timestamp with timestamp with Exactly the same as timestamp, but also stores an offset
time zone time zone from UTC of the time specified.

SQL Operators
Operator:
An operator is a special symbol which used to perform a specific operation.

SQL operators:
SQL operators are the reserved words or special symbols or characters that are used to
perform specific operations.

Types of SQL operators:


1. SQL Arithmetic Operators
2. SQL Comparison Operators
3. SQL Logical Operators

1. SQL Arithmetic Operators:


Let us consider the two variables a and b, where a hold 20 and b hold 40.
Operator Description Example
+ It is used to add the operands values. a + b will give 60
– It is used to subtract right hand operand from left hand a – b will give -
operand. 20
a * b will give
* It is used to multiply the operands values.
800
/ It is used to divide left hand operand by right hand operand b / a will give 2
It is used to modulo divide left hand operand by right hand
% b % a will give 0
operand.

2. SQL Comparison Operators:


Let us consider the two variables a and b, where a hold 20 and b hold 40.
Operator Description Example
It is used to check that the values of two operands are equal or (a = b) is not
=
not, if yes then condition becomes true. true.
It is used to check that the values of two operands are equal or (a != b) is
!=
not, if values are not equal then condition becomes true. true.
It is used to check that the values of two operands are equal or (a <> b) is
<>
not, if values are not equal then condition becomes true. true.
It is used to check that the value of left operand is greater than (a > b) is not
>
the value of right operand, if yes then condition becomes true. true.
It is used to check that the value of left operand is less than the (a < b) is
<
value of right operand, if yes then condition becomes true. true.
It is used to check that the value of left operand is greater than or
(a >= b) is
>= equal to the value of right operand, if yes then condition becomes
not true.
true.
It is used to check that the value of left operand is less than or
(a <= b) is
<= equal to the value of right operand, if yes then condition becomes
true.
true.
It is used to check that the value of left operand is not less than (a !< b) is
!<
the value of right operand, if yes then condition becomes true. false.
It is used to check that the value of left operand is not greater
(a !> b) is
!> than the value of right operand, if yes then condition becomes
true.
true.

3. SQL Logical Operators


Operator Description
ALL It is used to compare a value to all values in another value set.
It allows the existence of multiple conditions in an SQL statement’s WHERE
AND
clause.
It is used to compare a value to any applicable value in the list according to the
ANY
condition.
It is used to search for values that are within a set of values, given the minimum
BETWEEN
value and the maximum value.
It is used to search for the presence of a row in a specified table that meets
EXISTS
certain criteria.
IN The IN operator is used to compare a value to a list of literal values that have
been specified.
LIKE It is used to compare a value to similar values using wildcard operators.
It reverses the meaning of the logical operator with which it is used. Eg: NOT
NOT
EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
OR It is used to combine multiple conditions in an SQL statement’s WHERE clause.
IS NULL It is used to compare a value with a NULL value.
UNIQUE It searches every row of a specified table for uniqueness (no duplicates).

SQL CREATE Database


The SQL CREATE DATABASE statement is used to create a new database.
Syntax: CREATE DATABASE databaseName;
Note: Database name should be unique within the RDBMS.

Example:
CREATE DATABASE w3spoint_db;

SQL SHOW Database List


To show the list all existing databases in SQL schema we have to use SHOW DATABASES
statement.
Syntax:
SHOW DATABASES;

SQL SELECT Database


In case multiple databases exist in the SQL schema we have to select the database before
performing any operation. The USE statement is used to select any existing database in SQL
schema.
Syntax:
USE databaseName;

Example:
USE w3spoint_db;

SQL DROP Database


To delete or drop an existing database we have to use DROP DATABASE statement.
Syntax:
DROP DATABASE databaseName;

Example:
DROP DATABASE w3spoint_db;

SQL CREATE Table


Table:
A table in SQL is a set of data which is systematically displayed in rows and columns.
The CREATE TABLE Statement is used to create a new table.

Syntax:
CREATE TABLE tableName
(columnName1 datatype,
columnName2 datatype,
...

columnNameN datatype);
Example:
CREATE TABLE EMPLOYEE (

EMP_ID INT NOT NULL,

NAME VARCHAR (20) NOT NULL,

AGE INT NOT NULL,

SALARY INT NOT NULL,

PRIMARY KEY (EMP_ID)

);
Output:
Table created.
Note: We can use DESC command to see the created table.
DESC EMPLOYEE;
Table Column Data Type Length Precision Scale Primary Key
Nullable Default Comment
EMPLOYEE EMP_ID Number - - 0 1
- -
NAME Varchar 20 - 0 - -
-
AGE Number - - 0 - -
-
SALARY Number - - 0 -
- -

SQL ALTER Table


The ALTER TABLE statement is used to add, delete or modify a table column. It can also be
used to rename a table and to add or drop constraints on a table.

Syntax of ALTER TABLE to add a new column:


ALTER TABLE tableName ADD columnName datatype;

Example:
Syntax of ALTER TABLE to add multiple columns:
ALTER TABLE tableName ADD

(columnName1 datatype,

columnName2 datatype,

columnNameN datatype);
Example:
ALTER TABLE EMPLOYEE ADD (ADDRESS VARCHAR (20));
Output:
Table altered.
Syntax of ALTER TABLE to modify a column:
ALTER TABLE tableName MODIFY columnNme datatype;

Example:
ALTER TABLE EMPLOYEE MODIFY ADDRESS VARCHAR (25);
Output:
Table altered.
Syntax of ALTER TABLE to drop a column:
ALTER TABLE tableName DROP COLUMN columnName;

Example:
ALTER TABLE EMPLOYEE DROP COLUMN ADDRESS;
Output:
Table dropped.
Syntax of ALTER TABLE to rename a column:
ALTER TABLE tableName RENAME COLUMN oldColumnName to newColumnName;

Example:
ALTER TABLE EMPLOYEE RENAME COLUMN NAME to EMP_NAME;
Output:
Table altered.
Syntax of ALTER TABLE to DROP CONSTRAINT
from a table:
ALTER TABLE tableName DROP CONSTRAINT constraintName;

Example:
ALTER TABLE EMPLOYEE DROP CONSTRAINT SYS_C004697;
Output:
Table dropped.
SQL COPY Table
The SELECT INTO statement is used to copy a table data into another table.
Syntax:
Select * into destinationTable from sourceTable;

Example:
Select * into EMPLOYEE1 from EMPLOYEE;

SQL RENAME Table


The RENAME TABLE statement is used to change the table name.
Syntax:
RENAME tableName TO newTableName;
We can also use the ALTER TABLE statement to change the table name.
Syntax:
ALTER tableName RENAME TO newTableName;

Example:
RENAME EMPLOYEE1 TO EMPLOYEE2;

Or

ALTER EMPLOYEE1 RENAME TO EMPLOYEE2;


Example:
Statement processed.

SQL DROP Table


The DROP TABLE statement is used to delete an existing table definition, indexes,
constraints, access privileges and all associated data.
Note: When a table is deleted all the available information in the table will be lost,
so use it carefully.
Syntax:
DROP TABLE tableName;

Example:
DROP TABLE EMPLOYEE;
Output:
Table dropped.

SQL DELETE From Table


The DELETE statement is used to delete or remove all the rows from the table.
Syntax:
DELETE FROM tableName;

Example:
DELETE FROM EMPLOYEE;
Output:
3 row(s) deleted.
The DELETE statement with where condition is used to delete or remove the specific rows
from the table.
Syntax: DELETE FROM tableName [WHERE condition];

Example:
DELETE FROM EMPLOYEE WHERE EMP_ID = 5;
output:
1 row(s) deleted.

SQL TRUNCATE Table


The TRUNCATE TABLE command is used to remove the all rows from an existing table.
Syntax:
TRUNCATE TABLE tableName;

Example:
TRUNCATE TABLE EMPLOYEE;
Output:
Table truncated.
Difference between TRUNCATE, DELETE and DROP
commands:
The DELETE statement is used to delete or remove all the rows from the table. We can use
where clause to delete some specific rows. We can roll back the DELETE operation. DELETE
is slower than TRUCATE. It is a DML command. Table structure will not be lost.
The TRUNCATE statement is used to remove the all rows from an existing table. We can’t
roll back the TRUNCATE operation. TRUCATE is faster than DELETE. It is a DDL command.
Table structure will not be lost.
The DROP TABLE statement is used to delete an existing table definition, indexes,
constraints, access privileges and all associated data. We can’t roll back the DROP
operation. It is DDL command. Table structure will be lost.

SQL CONSTRAINTS
The SQL constraints are the rules enforced on the data in a table. A constraint can be
specified with the CREATE TABLE statement at the time table creation or we can specify it
with the ALTER TABLE statement after the table creation.

Syntax:
CREATE TABLE <em>tableName</em>
(
<em>columnName1 datatype</em>(<em>size</em>) <em>constraintName</em>,
<em>columnName2 data_type</em>(<em>size</em>) <em>constraintName</em>,
<em>columnName2 data_type</em>(<em>size</em>) <em>constraintName</em>,
....
);
Commonly used constraints in SQL:
1. SQL PRIMARY KEY Constraint.
2. SQL FOREIGN KEY.
3. SQL NOT NULL Constraint.
4. SQL UNIQUE Constraint.
5. SQL CHECK Constraint
6. SQL DEFAULT Constraint
7. SQL INDEX Constraint.

SQL PRIMARY KEY Constraint


The PRIMARY KEY constraint is used to uniquely identify each row in a table. A PRIMARY
KEY must contain unique values and it can’t contain a null value. A table can have only one
primary key. We can use multiple columns or fields to define a primary key, such primary
key is known as composite key.

Syntax of PRIMARY KEY Constraint on one column


with CREATE TABLE statement:
MySQL:
CREATE TABLE Persons
(
P_Id int NOT NULL,
FirstName varchar(25) NOT NULL,
LastName varchar(25),
Address varchar(255),
PRIMARY KEY (P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
FirstName varchar(25) NOT NULL,
LastName varchar(25),
Address varchar(255),
)
Syntax of PRIMARY KEY Constraint on one column
with ALTER TABLE statement:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE CUSTOMER ADD PRIMARY KEY(ID);
Syntax of PRIMARY KEY Constraint on multiple
columns with CREATE TABLE statement:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL,
FirstName varchar(25) NOT NULL,
LastName varchar(25),
Address varchar(255),
PRIMARY KEY (P_Id, FirstName)
)
Syntax of PRIMARY KEY Constraint on multiple
columns with ALTER TABLE statement:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons ADD CONSTRAINT PK_PersonID
PRIMARY KEY(P_Id, FirstName);
Delete PRIMARY KEY:
Use following syntax to delete the primary key.

MySQL:
ALTER TABLE Persons DROP PRIMARY KEY
SQL Server / Oracle / MS Access:
ALTER TABLE Persons DROP CONSTRAINT pk_PersonID

SQL FOREIGN KEY


The FOREIGN KEY is used to define a relationship between two tables and a FOREIGN KEY in
one table points to the PRIMARY KEY in another table.

Syntax of FOREIGN KEY Constraint on one column


with CREATE TABLE statement:
MySQL:
CREATE TABLE Orders
(
Order_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (Order_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Orders
(
Order_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)
Syntax of FOREIGN KEY Constraint on one column
with ALTER TABLE statement:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders DROP FOREIGN KEY fk_POrders
Syntax of FOREIGN KEY Constraint on one column
with CREATE TABLE statement:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders
(
Order_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (Order_Id),
CONSTRAINT fk_POrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
Syntax of FOREIGN KEY Constraint on one column
with ALTER TABLE statement:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders ADD CONSTRAINT fk_POrders
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
DropFOREIGNKEY:
Use following syntax to delete the foreign key.

MySQL:
ALTER TABLE Orders DROP FOREIGN KEY fk_POrders
SQL Server / Oracle / MS Access:
ALTER TABLE Orders DROP CONSTRAINT fk_POrders
Difference between primary key and foreign key:
Primary key Foreign key
1. Foreign key can contain null values.
1. Primary key can’t contain null values.
2. Foreign key can be duplicate.
2. Primary key can’t be duplicate.
3. A table can have more than one
3. A table can have only one primary key.
foreign key.
4. Primary key automatically adds a
4. Foreign key not add any index
clustered index.
automatically.

SQL NOT NULL Constraint


The NOT NULL constraint enforces a field or column to not contain a null value.

Example of NOT NULL constraint with CREATE


TABLE statement:
CREATE TABLE PERSONS (

P_ ID INT NOT NULL,

NAME VARCHAR (20) NOT NULL,

AGE INT,

PRIMARY KEY (P_ID)

);
Example of NOT NULL constraint with ALTER TABLE
statement:
ALTER TABLE PERSONS MODIFY AGE INT NOT NULL;

SQL UNIQUE Constraint


The UNIQUE constraint is used to uniquely identify each row in a table. It is like primary key
but it can contain one null value and a table can have more than one UNIQUE constraint.

Syntax of UNIQUE Constraint on one column with


CREATE TABLE statement:
MySQL:
CREATE TABLE Persons
(
P_Id int NOT NULL,
FirstName varchar(25) NOT NULL,
LastName varchar(25),
Address varchar(255),
UNIQUE (P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
FirstName varchar(25) NOT NULL,
LastName varchar(25),
Address varchar(255),
)
Syntax of UNIQUE Constraint on one column with
ALTER TABLE statement:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons ADD UNIQUE (P_Id)
Syntax of UNIQUE Constraint on multiple columns
with CREATE TABLE statement:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL,
FirstName varchar(25) NOT NULL,
LastName varchar(25),
Address varchar(255),
CONSTRAINT uc_PID UNIQUE (P_Id,FirstName)
)
Syntax of UNIQUE Constraint on multiple columns
with ALTER TABLE statement:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons ADD CONSTRAINT uc_PID UNIQUE (P_Id,FirstName)
Drop UNIQUE Constraint:
Use following syntax to drop the unique constraint.

MySQL:
ALTER TABLE Persons DROP INDEX uc_PID
SQL Server / Oracle / MS Access:
ALTER TABLE Persons DROP CONSTRAINT uc_PID

SQL INDEX Constraint


The INDEX is used to create and retrieve data from the table very quickly. An INDEX is
created with CREATE INDEX statement.
Syntax:
CREATE INDEX indexName ON tableName (column1, column2.....);

Drop an INDEX Constraint:


Use the following syntax to drop an index constraint.
ALTER TABLE tableName DROP INDEX indexName;

SQL INSERT Statement


The INSERT statement is used to insert a new record into the table.

Ways to insert the data into a table:


1. Inserting the data directly to a table.
2. Inserting data to a table through a select statement.

1. Inserting the data directly to a table.


In case when we insert the values in the specified columns.
Syntax:
INSERT INTO tableName [(column1, column2,..., columnN)] VALUES (value1,
value2,...,valueN);

Example:
INSERT INTO EMPLOYEE (EMP_ID, EMP_NAME, AGE, SALARY)
VALUES (1, 'Parbhjot',28,35000);
Output:
1 row(s) inserted.
2. In case when we insert the values in all columns.
Syntax:
INSERT INTO tableName VALUES (value1, value2,...,valueN);
We can ignore the column names if we want to insert the values in all columns of the table.

Example:
INSERT INTO EMPLOYEE VALUES (5, 'Nidhi',28,45000);
Output:
1 row(s) inserted.
2. Inserting data to a table through a select
statement.
In case when we insert the values in the specified columns.
Syntax:
INSERT INTO destinationTableName [(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM sourceTableName WHERE [condition];

Example:
INSERT INTO EMPLOYEE1 (EMP_ID, EMP_NAME, AGE, SALARY)
SELECT EMP_ID, EMP_NAME, AGE, SALARY
FROM EMPLOYEE WHERE EMP_ID = '1';
Output:
1 row(s) inserted.
In case when we insert the values in all columns.
Syntax:
INSERT INTO destinationTableName SELECT * FROM sourceTableName;

Example:
INSERT INTO EMPLOYEE1 SELECT * FROM EMPLOYEE WHERE EMP_ID = '5';
Output:
1 row(s) inserted.

SQL UPDATE Statement


The UPDATE statement is used to modify the existing record in a table.
Syntax:
UPDATE tableName SET columnName1 = value1, columnName2 = value2,..., columnNameN
= valueN
WHERE [condition]
Use where condition if you want to update a specific record otherwise all records will
update.

Example:
UPDATE EMPLOYEE SET EMP_NAME = 'Parmender' WHERE EMP_ID = '5';
Output:
1 row(s) updated.

SQL SELECT
The SELECT statement is used to retrieve the data from a database table in the form of
result sets.

Syntax of SELECT to fetch all columns:


SELECT * FROM tableName;

Example:
SELECT * FROM EMPLOYEE;
Output:
EMP_ID EMP_NAME AGE SALARY
1 Parbhjot 28 35000
5 Parmender 28 45000
2 Parmender 30 45000
3 Nidhi 28 48000
4 Parbhjot 29 46000
Syntax of SELECT to fetch specific columns:
SELECT column1, column2, columnN FROM tableName;

Example:
SELECT EMP_ID, EMP_NAME FROM EMPLOYEE;
Output:
EMP_ID EMP_NAME
1 Parbhjot
5 Parmender
2 Parmender
3 Nidhi
4 Parbhjot

SQL UNIQUE Keyword


The UNIQUE keyword is used to retrieve the unique records by eliminating the all duplicate
records.

Syntax:
SELECT UNIQUE column1, column2,.....columnN FROM tableName WHERE [condition]
UNIQUE and DISTINCT statements are same and will give the same result sets.

Example:
SELECT UNIQUE EMP_NAME FROM EMPLOYEE;
Output:
EMP_NAME
Nidhi
Parbhjot
Parmender

SQL DISTINCT Keyword


The DISTINCT keyword is used to retrieve the unique records by eliminating the all
duplicate records.

Syntax:
SELECT DISTINCT column1, column2,.....columnN FROM tableName WHERE [condition]

Example:
SELECT DISTINCT EMP_NAME FROM EMPLOYEE;
Output:
EMP_NAME
Nidhi
Parbhjot
Parmender

SQL SELECT TOP


The SELECT TOP statement is used to retrieve the top specified number of rows from a
table.

Syntax:
SELECT TOP n * FROM tableName
Where n is the number of rows.

Example:
SELECT TOP 2 * FROM EMPLOYEE;
Output:
EMP_ID EMP_NAME AGE SALARY
1 Parbhjot 28 35000
5 Parmender 28 45000

SQL SELECT IN Operator


The IN operator is used to reduce the multiple or conditions by specifying the multiple
values in a where clause.

Syntax:
SELECT * FROM tableName WHERE columnName
IN (value1,value2,... valueN);
The value of the conditioned column should be equal to the any one of the specified values
in the IN operator.
Example:
SELECT * FROM EMPLOYEE WHERE EMP_ID IN (1,2,5);
Output:
EMP_ID EMP_NAME AGE SALARY
1 Parbhjot 28 35000
5 Parmender 28 45000
2 Parmender 28 45000

SQL NOT IN Operator


The NOT IN operator is used to reduce the multiple or conditions by specifying the multiple
values in a where clause.

Syntax:
SELECT * FROM tableName WHERE columnName
NOT IN (value1,value2,... valueN);
The value of the conditioned column should not be equal to the any of the specified values
in the NOT IN operator.

Example:
SELECT * FROM EMPLOYEE WHERE EMP_ID NOT IN (1,2,5);
Output:
EMP_ID EMP_NAME AGE SALARY
3 Nidhi 28 48000
4 Parbhjot 29 46000

SQL BETWEEN Operator


The BETWEEN operator is used to select values within a range. The values can be numbers,
dates or text.

Syntax:
SELECT * FROM tableName WHERE columnName BETWEEN value1 AND value2;
The value of the conditioned column should be in the given range specified by BETWEEN
operator.

Example:
SELECT * FROM EMPLOYEE WHERE SALARY BETWEEN 40000 AND 50000;
Output:
EMP_ID EMP_NAME AGE SALARY
5 Parmender 28 45000
3 Nidhi 28 48000
4 Parbhjot 29 46000
2 Parmender 28 45000

SQL NOT BETWEEN Operator


The BETWEEN operator is used to select values within a range. The values can be numbers,
dates or text.

Syntax:
SELECT * FROM tableName WHERE columnName NOT BETWEEN value1 AND value2;
The value of the conditioned column should not be in the given range specified by NOT
BETWEEN operator.

Example:
SELECT * FROM EMPLOYEE WHERE SALARY NOT BETWEEN 40000 AND 50000;
Output:
EMP_ID EMP_NAME AGE SALARY
1 Parbhjot 28 35000

SQL ALIAS Statement


The ALIAS statement is used to temporarily rename a table or column in a SQL statement.

Syntax:
SELECT columnName AS columnAliasName FROM tableName As tableAliasName;

Example:
SELECT EMP_NAME AS NAME FROM EMPLOYEE WHERE EMP_ID = 1;
Output:
NAME
Parbhjot

SQL WHERE Clause


The WHERE clause is used to add a condition to filter the records when we want to fetch the
specific records instead of all records.

Syntax:
SELECT * FROM tableName WHERE [condition];
To specify a condition we can use any logical operator like >, <, =, LIKE, NOT etc.

Example:
SELECT * FROM EMPLOYEE WHERE EMP_ID = 1;
Output:
EMP_ID EMP_NAME AGE SALARY
1 Parbhjot 28 35000

SQL AND Clause


The AND clause is also known as conjunctive operator and used to combine multiple
conditions in SQL statement.

Syntax:
SELECT * FROM tableName WHERE [condition1] AND [condition2]...AND [conditionN];
In case of AND clause all conditions should be true.

Example:
SELECT * FROM EMPLOYEE WHERE SALARY > 40000 AND AGE < 29;
Output:
EMP_ID EMP_NAME AGE SALARY
5 Parmender 28 45000
3 Nidhi 28 48000
2 Parmender 28 45000

SQL OR Clause
The OR clause is also known as conjunctive operator and used to combine multiple
conditions in SQL statement.

Syntax:
SELECT * FROM tableName WHERE [condition1] OR [condition2]...OR [conditionN];
In case of OR clause any one of the conditions separated by OR should be true.

Example:
SELECT * FROM EMPLOYEE WHERE SALARY > 40000 OR AGE < 29;
Output:
EMP_ID EMP_NAME AGE SALARY
1 Parbhjot 28 35000
5 Parmender 28 45000
3 Nidhi 28 48000
4 Parbhjot 29 46000
2 Parmender 28 45000

SQL UNION Operator


SQL UNION Operator.
The UNION operator is used to combine the result sets of two or more SELECT statements.
For UNION, every SELECT statement must have same number of columns with same data
type and must be in same order. It will return the distinct values by removing the duplicate
rows.

Syntax:
SELECT columnList FROM table1 UNION SELECT columnList FROM table2;

Example:
SELECT EMP_NAME, SALARY FROM EMPLOYEE
UNION
SELECT EMP_NAME, AGE FROM EMPLOYEE1;
Output:
EMP_NAME SALARY
Nidhi 28
Nidhi 48000
Parbhjot 28
Parbhjot 35000
Parbhjot 46000
Parmender 45000
SQL UNION ALL Operator.
It works same as UNION operator only difference is that it returns the duplicate rows.

Syntax:
SELECT columnList FROM table1 UNION ALL SELECT columnList FROM table2;

Example:
SELECT EMP_NAME, SALARY FROM EMPLOYEE
UNION ALL
SELECT EMP_NAME, AGE FROM EMPLOYEE1;
Output:
EMP_NAME SALARY
Parbhjot 35000
Parmender 45000
Nidhi 48000
Parbhjot 46000
Parmender 45000
Parbhjot 28
Nidhi 28

SQL LIKE Operator


The LIKE operator is used in a WHERE clause to retrieve all records of a table whose
specified column values match a specified pattern. The percent sign (%) and underscore (_)
are two wildcards used in the LIKE operator pattern. The underscore represents a single
character and percent sign represents the multiple characters.

Syntax:
SELECT * FROM tableName WHERE columnName LIKE pattern;

Example:
SELECT * FROM EMPLOYEE WHERE EMP_NAME LIKE 'P%';
Output:
EMP_ID EMP_NAME AGE SALARY
1 Parbhjot 28 35000
5 Parmender 28 45000
4 Parbhjot 29 46000
2 Parmender 28 45000

SQL ORDER BY Clause


The ORDER BY Clause is used to sort the results either in ascending or descending order
based on one or more columns.
Oracle and some other database sorts query results in ascending order by default.
Syntax:
SELECT * FROM tableName [WHERE condition] [ORDER BY column1, column2,...,columnN]
[ASC | DESC];
Where ASC keyword is used for ascending order and DESC keyword is used for descending
order.

Example:
SELECT * FROM EMPLOYEE ORDER BY EMP_NAME;
Output:
EMP_ID EMP_NAME AGE SALARY
3 Nidhi 28 48000
4 Parbhjot 29 46000
1 Parbhjot 28 35000
5 Parmender 28 45000
2 Parmender 28 45000

SQL GROUP BY Clause


The GROUP BY clause is used to group the identical data by one or more columns. It is used
with the aggregate functions in the select statement.
Syntax:
SELECT column1, column2,…, columnN FROM tableName
WHERE[conditions] GROUP BY column1, column2 …;

Example:
SELECT EMP_NAME, SUM(SALARY) FROM EMPLOYEE GROUP BY EMP_NAME;
Output:
EMP_NAME SUM(SALARY)
Nidhi 48000
Parbhjot 81000
Parmender 90000

SQL HAVING Clause


The HAVING clause is used with the GROUP BY clause and filter the groups created by the
GROUP BY clause.

Syntax:
SELECT column1, column2,…, columnN FROM tableName WHERE[conditions]
GROUP BY column1, column2 …HAVING[conditions];

Example:
SELECT EMP_NAME, SUM(SALARY) FROM EMPLOYEE
GROUP BY EMP_NAME HAVING Count(EMP_NAME) >= 2;
Output:
EMP_NAME SUM(SALARY)
Parbhjot 81000
Parmender 90000
Position of different clauses in a SQL statement:
1. SELECT
2. FROM
3. WHERE
4. GROUP BY
5. HAVING
6. ORDER BY

SQL JOIN Clause


The JOIN are used to combine the records from two or more tables.

Types of SQL JOIN:


1. SQL INNER JOIN.
2. SQL LEFT OUTER JOIN.
3. SQL RIGHT OUTER JOIN.
4. SQL FULL OUTER JOIN.
5. SQL SELF JOIN.
6. SQL CARTESIAN JOIN or CROSS JOIN.

SQL INNER JOIN


The INNER JOIN returns the all records from the both tables for which the join condition is
true. It is also known as EQUIJOIN.

Syntax:
SELECT columnList FROM table1 INNER JOIN table2 ON table1.columnName =
table2.columnName;
or
SELECT columnList FROM table1 JOIN table2 ON table1.columnName =
table2.columnName;

Example:
SELECT P_ID, NAME, AMOUNT

FROM PERSONS

INNER JOIN ORDERS

ON PERSONS.P_ID = ORDERS.PERSON_ID;
Output:
P_ID NAME AMOUNT
3 deepak 25000
3 deepak 23000
2 sandy 22000
2 sandy 30000
SQL LEFT OUTER JOIN
The LEFT OUTER JOIN returns the all records of left table and matching records of right
table. When no match is found right table columns will be return with the null values.

Syntax:
SELECT columnList FROM table1 LEFT OUTER JOIN table2 ON table1.columnName =
table2.columnName;
or
SELECT columnList FROM table1 LEFT JOIN table2 ON table1.columnName =
table2.columnName;

Example:
SELECT P_ID, NAME, AMOUNT

FROM PERSONS

LEFT OUTER JOIN ORDERS

ON PERSONS.P_ID = ORDERS.PERSON_ID;
Output:
P_ID NAME AMOUNT
3 deepak 25000
3 deepak 23000
2 sandy 22000
2 sandy 30000
4 Ashish -
1 jai -

SQL RIGHT OUTER JOIN


The RIGHT OUTER JOIN returns the all records of right table and matching records of left
table. When no match is found left table columns will be return with the null values.

Syntax:
SELECT columnList FROM table1 RIGHT OUTER JOIN table2 ON table1.columnName =
table2.columnName;
or
SELECT columnList FROM table1 RIGHT JOIN table2 ON table1.columnName =
table2.columnName;

Example:
SELECT P_ID, NAME, AMOUNT

FROM PERSONS

RIGHT OUTER JOIN ORDERS

ON PERSONS.P_ID = ORDERS.PERSON_ID;
Output:
P_ID NAME AMOUNT
2 sandy 30000
2 sandy 22000
3 deepak 23000
3 deepak 25000

SQL FULL OUTER JOIN


The FULL OUTER JOIN returns the result of the combination of left and right outer joins.

Syntax:
SELECT columnList FROM table1 FULL OUTER JOIN table2 ON table1.columnName =
table2.columnName;

Example:
SELECT P_ID, NAME, AMOUNT

FROM PERSONS

FULL OUTER JOIN ORDERS

ON PERSONS.P_ID = ORDERS.PERSON_ID;
Output:
P_ID NAME AMOUNT
1 jai -
2 sandy 30000
2 sandy 22000
3 deepak 23000
3 deepak 25000
4 Ashish -

SQL SELF JOIN


The SELF JOIN is used to join the table to itself that why it is known as SELF JOIN.

Syntax:
SELECT columnList FROM table1 t1, table1 t2 WHERE t1.commonColumn = t2.
commonColumn;

Example:
SELECT emp1.EMP_NAME FROM EMPLOYEE emp1, EMPLOYEE emp2
WHERE emp1.AGE = emp2.AGE;
Output:
EMP_NAME
Parmender
Nidhi
Parmender
Parbhjot
Parmender
Nidhi
Parmender
Parbhjot
Parmender
Nidhi

SQL CARTESIAN JOIN


The CARTESIAN JOIN or CROSS JOIN return the data by joining the every row of one table
to every row of another table i.e it returns the Cartesian product of two tables.

Syntax:
SELECT columnList FROM table1 t1, table1 t2;

Example:
SELECT * FROM PERSONS FULL OUTER JOIN ORDERS
ON PERSONS.P_ID = ORDERS.PERSON_ID;
Output:
P_ID NAME AGE SALARY ORDER_ID ORDERNO PERSON_ID AMOUNT
1 jai 27 50000 - - - -
2 sandy 28 45000 4 3 2 30000
2 sandy 28 45000 3 1 2 22000
3 deepak 27 42000 2 21 3 23000
3 deepak 27 42000 1 12 3 25000
4 Ashish 28 46000 - - - -

SQL Functions
SQL provides no. of inbuilt functions which perform calculations on groups of rows and
return one value for the whole group.

Commonly used SQL functions:


1. SQL AVG(): It is used to get the average value of a numeric column.
Syntax:
SELECT AVG(columnName) FROM tableName;

2. SQL COUNT(): It is used to get the number of rows that matches a specified criteria.
Syntax:
SELECT COUNT(columnName) FROM tableName;

3. SQL FIRST(): It is used to get the first value of the selected column.
Syntax:
SELECT FIRST(columnName) FROM tableName;

4. SQL LAST(): It is used to get the last value of the selected column.
Syntax:
SELECT LAST(columnName) FROM tableName;

5. SQL MAX(): It is used to get the largest value of the selected column.
Syntax:
SELECT MAX(columnName) FROM tableName;
6. SQL MIN(): It is used to get the smallest value of the selected column.
Syntax:
SELECT MIN(columnName) FROM tableName;

7. SQL SUM(): It is used to get the total sum of a numeric column.


Syntax:
SELECT SUM(columnName) FROM tableName;

You might also like