C, Java, SQL 1
C, Java, SQL 1
C, Java, SQL 1
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++:
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
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);
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
1. Array
2. Pointer
3. Structure
4. Union
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:
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:
int main()
{
// Performing Arithmetic Operations without using brackets.
int sum1 = 10+20*10-90*10+700;
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;
void main()
{
int sum = 100;
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;
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;
}
void main()
{
int i = 1;
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);
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;
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;
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:
Syntax:
Return_type functionName(parameters)
{
code to be executed;
}
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!
Call by Value
Call by Reference
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:
Example:
#include<stdio.h>
void demo()
{
static int i=0;
register int j=0;
auto int k=0;
i++;
j++;
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.
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
void main()
{
int a[10][10],b[10][10],c[10][10],r1,c1,r2,c2,i,j;
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
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];
}
}
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>
void main()
{
int i=0,max=0;
int array[] ={9,52,77,635,889,679,6,54,78,34};
max = maximum(array,10);
printf("\nLargest Number is: %d",max);
}
Output
List of Numbers:
9
52
77
635
889
679
6
54
78
34
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:
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
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
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");
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
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");
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");
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);
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,
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.
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
Java was modeled in its final form keeping in consideration with the primary objective of having
the following features:
Object-Oriented
Architectural-neutral
High Performance
Multi-Threaded
Distributed
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0 8 byte
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
OPERATORS IN JAVA
Java supports a rich set of operators that can be classified into categories as below :
Assignment operator =, +=, −=, ×=, ÷=, %=, &=, ^=, |=, <<=, >>=, >>>=
Conditional operators ?:
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
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
void someMethod()
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
METHODS 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;
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);
}
}
An object-oriented paradigm offers the following concepts to simplify software development and
maintenance.
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.
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).
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
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();
}
}
void area()
{
int a =4;
System.out.printf("Area of Square with side 4= %d %n", a * a);
}
● 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.
1. Number of parameters
example: add(int, int)
add(int, int, int)
class Shape
{
void area()
{
System.out.println("Area of the following shapes are : ");
}
}
12
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
//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.
interface Area
{
final static float pi = 3.14F;
float compute(float x , float y);
}
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();
CONSTRUCTORS IN JAVA
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[]) {
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.
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);
class MatrixArray
18
//printing matrix
for(int a=0;a<=m1.length;a++)
for(int b=0;b<=m2.length;b++)
System.out.println();
//matrix addition
for(int a=0;a<=m1.length;a++)
for(int b=0;b<=m2.length;b++)
System.out.println();
STRINGS IN JAVA
Creating 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
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]);
} }
}
● 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.
MULTITHREADING
● Process-based multitasking.(Multitasking)
● Thread-based multitasking (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.
Process has to switch between different programs Processor needs to switch between different
or processes. parts or threads of the program.
program or process in the smallest unit in the thread is the smallest unit
environment
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
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 stop() to cause premature death of thread, thus moving it to dead state.
{
for(int i=1;i<=5;i++)
{
System.out.println("From thread A : i " + i);
}
System.out.println("Exit from A ");
}
}
{
for(int i=0;i<=5;i++)
{
System.out.println("From thread B : i " + i);
}
System.out.println("Exit from B ");
}
}
class ThreadTest
{
public static void main(String args[])
{
25
new A().start();
new B().start();
new C().start();
}
}
The run( ) method that is declared in the Runnable interface which is required for implementing
threads in our programs.
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
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.
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 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.
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);
}
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
● 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.
● Creating files
● Updating files
● Manipulation of data
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.
● 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
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 :
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(byte b [ ], int n, int m) Reads m bytes into b starting from the nth byte of b
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(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
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:
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'};
System.exit(-1);
}
}
}
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 ]);
READING/WRITING CHARACTERS
The two subclasses of Reader and Writer classes for handling characters in files are FileReader
and FileWriter.
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
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
CLASSES
The classes available in the collection framework implement the collection interface and
sub-interfaces. They also implement Map and Iterator interfaces.
Class Interface
AbstractCollection Collection
AbstarctList List
Abstract Queue
AbstractSequentialList List
LinkedList List
AbstractSet Set
EnumSet Set
HashSet Set
PriorityQueue Queue
TreeSet Set
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);
//getting size
System.out.println("Size of array list is: ");
num.size();
//removing an element
num.remove(4);
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);
}
}
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);
}
}
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);
}
}
}
import java.util.*;
st.push("Objects");
st.push("Multithreading");
st.push("Programming");
import java.util.*;
Enumeration e = ht.keys();
while(e.hasMoreElements())
{
String str = (String) e.nextElement();
System.out.println(ht.get(str));
}
}
}
Memory management is :
40
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
dia = 2*r;
peri = 2*Math.PI*r;
area = Math.PI*r*r;
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();
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);
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 !!!! ****** ");
}
}
}
import java.util.Scanner;
class Palindrome
{
public static void main(String args[])
{
int num,reverse=0,mode;
Scanner s = new Scanner(System.in);
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.
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 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.
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.
Example:
CREATE DATABASE w3spoint_db;
Example:
USE w3spoint_db;
Example:
DROP DATABASE w3spoint_db;
Syntax:
CREATE TABLE tableName
(columnName1 datatype,
columnName2 datatype,
...
columnNameN datatype);
Example:
CREATE TABLE EMPLOYEE (
);
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 -
- -
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;
Example:
RENAME EMPLOYEE1 TO EMPLOYEE2;
Or
Example:
DROP TABLE EMPLOYEE;
Output:
Table dropped.
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.
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.
MySQL:
ALTER TABLE Persons DROP PRIMARY KEY
SQL Server / Oracle / MS Access:
ALTER TABLE Persons DROP CONSTRAINT pk_PersonID
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.
AGE INT,
);
Example of NOT NULL constraint with ALTER TABLE
statement:
ALTER TABLE PERSONS MODIFY AGE INT NOT NULL;
MySQL:
ALTER TABLE Persons DROP INDEX uc_PID
SQL Server / Oracle / MS Access:
ALTER TABLE Persons DROP CONSTRAINT uc_PID
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.
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.
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
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
Syntax:
SELECT DISTINCT column1, column2,.....columnN FROM tableName WHERE [condition]
Example:
SELECT DISTINCT EMP_NAME FROM EMPLOYEE;
Output:
EMP_NAME
Nidhi
Parbhjot
Parmender
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
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
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
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
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
Syntax:
SELECT columnName AS columnAliasName FROM tableName As tableAliasName;
Example:
SELECT EMP_NAME AS NAME FROM EMPLOYEE WHERE EMP_ID = 1;
Output:
NAME
Parbhjot
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
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
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
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
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
Example:
SELECT EMP_NAME, SUM(SALARY) FROM EMPLOYEE GROUP BY EMP_NAME;
Output:
EMP_NAME SUM(SALARY)
Nidhi 48000
Parbhjot 81000
Parmender 90000
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
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
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
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 -
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
ON PERSONS.P_ID = ORDERS.PERSON_ID;
Output:
P_ID NAME AMOUNT
2 sandy 30000
2 sandy 22000
3 deepak 23000
3 deepak 25000
Syntax:
SELECT columnList FROM table1 FULL OUTER JOIN table2 ON table1.columnName =
table2.columnName;
Example:
SELECT P_ID, NAME, AMOUNT
FROM PERSONS
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 -
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
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.
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;