Sie sind auf Seite 1von 115

Cryolite India Softwares Pvt. Ltd.

C Programming Language Notes

C Programming Language Tutorial

C language Tutorial with programming approach for beginners and professionals, helps you
to understand the C language tutorial easily. Our C tutorial explains each topic with programs.

The C Language is developed for creating system applications that direct interacts to the
hardware devices such as drivers, kernals etc.

C programming is considered as the base for other programming languages, that is why it is
known as mother language.

It can be defined by following ways:

1. Mother language

2. System programming language

3. Procedure-oriented programming language

4. Structured programming language

5. Mid level programming language

1) C as a mother language
C language is considered as the mother language of all the modern languages because most
of the compilers, JVMs, Kernals etc. are written in C language and most of languages
follows c syntax e.g. C++, Java etc.

It provides the core concepts like array, functions, file handling etc. that is being used in many
languages like C++, java, C# etc.

2) C as a system programming language


A system programming language is used to create system softwares. C language is a system
programming language because it can be used to do low level programming (e.g. driver
and kernel). It is generally used to create hardware devices, OS, drivers, kernels etc. For
example, linux kernel is written in C.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

It can’t be used in internet programming like java, .net, php etc.

3) C as a procedural language
A procedure is known as function, method, routine, subroutine etc. A procedural
language specifies a series of steps or procedures for the program to solve the
problem.

A procedural language breaks the program into functions, data structures etc.

C is a procedural language. In C, variables and function prototypes must be declared before


being used.

4) C as a structured programming language


A structured programming language is a subset of procedural language. Structure means
to break a program into parts or blocks so that it may be easy to understand.

In C language, we break the program into parts using functions. It makes the program easier
to understand and modify.

5) C as a mid-level programming language


C is considered as a middle level language because it supports the feature of both low-
level and high level language. C language program is converted into assembly code,
supports pointer arithmetic (low level), but it is machine independent (feature of high level).

Low level language is specific to one machine i.e. machine dependent. It is machine
dependent, fast to run. But it is not easy to understand.

High Level language is not specific to one machine i.e. machine independent. It is easy to
understand.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

History of C Language

C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of


AT&T (American Telephone & Telegraph), located in U.S.A.

Dennis Ritchie is known as the founder of c language.

It was developed to overcome the problems of previous languages such as B, BCPL etc.

Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.

Let's see the programming languages that were developed before C language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Features of C Language

C is the widely used language. It provides a lot of features that are given below.

1. Simple

2. Machine Independent or Portable

3. Mid-level programming language

4. structured programming language

5. Rich Library

6. Memory Management

7. Fast Speed

8. Pointers

9. Recursion

10. Extensible

1) Simple
C is a simple language in the sense that it provides structured approach (to break the
problem into parts), rich set of library functions, data typesetc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed in many machines with little bit
or no change. But it is not platform-independent.

3) Mid-level programming language


C is also used to do low level programming. It is used to develop system applications
such as kernel, driver etc. It also supports the feature of high level language. That is
why it is known as mid-level language.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

4) Structured programming language


C is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify.

5) Rich Library
C provides a lot of inbuilt functions that makes the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C language is fast.

8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array etc.

9) Recursion
In c, we can call the function within the function. It provides code reusability for every
function.

10) Extensible
C language is extensible because it can easily adopt new features.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

How to install C
There are many compilers available for c and c++. You need to download any one. Here, we
are going to use Turbo C++. It will work for both C and C++. To install the Turbo C software,
you need to follow following steps.

1. Download Turbo C++

2. Create turboc directory inside c drive and extract the tc3.zip inside c:\turboc

3. Double click on install.exe file

4. Click on the tc application file located inside c:\TC\BIN to write the c program

1) Download Turbo C++ software


You can download turbo c++ from many sites. download Turbo c++

2) Create turbo c directory in c drive and extract the


tc3.zip
Now, you need to create a new directory turboc inside the c: drive. Now extract the tc3.zip
file in c:\truboc directory.

3) Double click on the install.exe file and follow


steps
Now, click on the install icon located inside the c:\turboc

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

It will ask you to install c or not, press enter to install.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Change your drive to c, press c.

Press enter, it will look inside the c:\turboc directory for the required files.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Select Start installation by the down arrow key then press enter.

Now C is installed, press enter to read documentation or close the


software.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

4) Click on the tc application located inside


c:\TC\BIN
Now double click on the tc icon located in c:\TC\BIN directory to write the c program.

In windows 7 or window 8, it will show a dialog block to ignore and close the application
because fullscreen mode is not supported. Click on Ignore button.

Now it will showing following console.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

First C Program
Before starting the abcd of C language, you need to learn how to write, compile and run the
first c program.

To write the first c program, open the C console and write the following code:

1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }

#include <stdio.h> includes the standard input output library functions. The printf()
function is defined in stdio.h .

int main() The main() function is the entry point of every program in c language.

printf() The printf() function is used to print data on the console.

return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.

How to compile and run the c program


There are 2 ways to compile and run the c program, by menu and by shortcut.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

By menu
Now click on the compile menu then compile sub menu to compile the c program.

Then click on the run menu then run sub menu to run the c program.

By shortcut
Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.

You can view the user screen any time by pressing the alt+f5 keys.

Now press Esc to return to the turbo c++ console.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Flow of C Program
The C program follows many steps in execution. To understand the flow of C program well,
let us see a simple program first.

File: simple.c

1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }

Execution Flow

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Let's try to understand the flow of above program by the figure given below.

1) C program (source code) is sent to preprocessor first. The preprocessor is responsible to


convert preprocessor directives into their respective values. The preprocessor generates an
expanded source code.

2) Expanded source code is sent to compiler which compiles the code and converts it into
assembly code.

3) The assembly code is sent to assembler which assembles the code and converts it into
object code. Now a simple.obj file is generated.

4) The object code is sent to linker which links it to the library such as header files. Then it is
converted into executable code. A simple.exe file is generated.

5) The executable code is sent to loader which loads it into memory and then it is executed.
After execution, output is sent to console.

printf() and scanf() in C


The printf() and scanf() functions are used for input and output in C language. Both functions
are inbuilt library functions, defined in stdio.h (header file).

printf() function
The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

1. printf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function
The scanf() function is used for input. It reads the input data from the console.

1. scanf("format string",argument_list);

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Variables in C
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

1. type variable_list;

The example of declaring variable is given below:

1. int a;
2. float b;
3. char c;

Here, a, b, c are variables and int,float,char are data types.

We can also provide values while declaring the variables as given below:

1. int a=10,b=20;//declaring 2 variable of integer type


2. float f=20.8;
3. char c='A';

Rules for defining variables


o A variable can have alphabets, digits and underscore.

o A variable name can start with alphabet and underscore only. It can't start with digit.

o No white space is allowed within variable name.

o A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

Inalid variable names:

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

1. int 2;
2. int a b;
3. int long;

Types of Variables in C
There are many types of variables in c:

1. local variable

2. global variable

3. static variable

4. automatic variable

5. external variable

Local Variable
A variable that is declared inside the function or block is called local variable.

It must be declared at the start of the block.

1. void function1(){
2. int x=10;//local variable
3. }

You must have to initialize the local variable before it is used.

Global Variable
A variable that is declared outside the function or block is called global variable. Any function
can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

1. int value=20;//global variable


2. void function1(){
3. int x=10;//local variable
4. }

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Static Variable
A variable that is declared with static keyword is called static variable.

It retains its value between multiple function calls.

#include<stdio.h>

int fun()

static int count = 0;

count++;

return count;

int fun2()

int x=0;

x++;

return x;

int main()

printf("value of static variable first time is %d ", fun());

printf("\nvalue of static variable second time is %d ", fun());

printf("\nvalue of static variable third time is %d ", fun());

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

printf("\nvalue of local variable first time is %d ", fun2());

printf("\nvalue of local variable second time is %d ", fun2());

return 0;

If you call this function many times, local variable will print the same value for each
function call e.g, 1,1,1 and so on. But static variable will print the incremented value in
each function call e.g. 1, 2, 3 and so on.

Automatic Variable
All variables in C that is declared inside the block, are automatic variables by default. By we
can explicitly declare automatic variable using auto keyword.

1. void main(){
2. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }

External Variable
We can share a variable in multiple C source files by using external variable. To declare a
external variable, you need to use extern keyword.

myfile.h

1. extern int x=10;//external variable (also global)


program1.c

1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character etc.

There are 4 types of data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Basic Data Types


The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit operating system.

Let's see the basic data types. Its size is given according to 32 bit architecture.

Data Types Memory Size Range

Char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

Short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

Int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

Float 4 byte

Double 8 byte

long double 10 byte

Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name etc.
There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

Auto break case char const continue default do

double else enum extern float for goto if

Int long register return short signed sizeof Static

struct switch typedef union unsigned void volatile While

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

C Operators
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise etc.

There are following types of operators to perform different types of operations in C language.

o Arithmetic Operators

o Relational Operators

o Shift Operators

o Logical Operators

o Bitwise Operators

o Ternary or Conditional Operators

o Assignment Operator

o Misc Operator

Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right
to left.

Let's understand the precedence by the example given below:

1. int value=10+20*10;

The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= 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 ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Comments in C
Comments in C language are used to provide information about lines of code. It is widely used
for documenting code. There are 2 types of comments in C language.

1. Single Line Comments

2. Multi Line Comments

Single Line Comments


Single line comments are represented by double slash \\. Let's see an example of single line
comment in C.

1. #include<stdio.h>
2. int main(){
3. //printing information
4. printf("Hello C");
5. return 0;
6. }

Output:

Hello C

Even you can place comment after statement. For example:

1. printf("Hello C");//printing information

Mult Line Comments


Multi line comments are represented by slash asterisk \* ... *\. It can occupy many lines of
code but it can't be nested. Syntax:

1. /*
2. code

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

3. to be commented
4. */

Let's see an example of multi line comment in C.

1. #include<stdio.h>
2. int main(){
3. /*printing information
4. Multi Line Comment*/
5. printf("Hello C");
6. return 0;
7. }

Output:

Hello C

Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20,
'a', 3.4, "c programming" etc.

There are different types of constants in C programming.

List of Constants in C
Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc.

C const keyword
The const keyword is used to define constant in C programming.

1. const float PI=3.14;

Now, the value of PI variable can't be changed.

1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. printf("The value of PI is: %f",PI);
5. return 0;
6. }

Output:

The value of PI is: 3.140000

If you try to change the the value of PI, it will render compile time error.

1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. PI=4.5;
5. printf("The value of PI is: %f",PI);
6. return 0;
7. }

Output:

Compile Time Error: Cannot modify a const object

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

C if else Statement
The if statement in C language is used to perform operation on the basis of condition. By
using if-else statement, you can perform operation either condition is true or false.

There are many ways to use if statement in C language:

o If statement

o If-else statement

o If else-if ladder

o Nested if

If Statement
The single if statement in C language is used to execute the code if condition is true. The
syntax of if statement is given below:

1. if(expression){
2. //code to be executed
3. }

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Flowchart of if statement in C

Let's see a simple example of c language if statement.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. return 0;
10. }
Output
enter a number:4
4 is even number
enter a number:5

If-else Statement
The if-else statement in C language is used to execute the code if condition is true or false.
The syntax of if-else statement is given below:

1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

5. }
Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. else{
10. printf("%d is odd number",number);
11. }
12. return 0;
13. }
Output
enter a number:4

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

4 is even number
enter a number:5
5 is odd number

If else-if ladder Statement


The if else-if statement is used to execute one code from multiple conditions. The syntax of
if else-if statement is given below:

1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number==10){
7. printf("number is equals to 10");
8. }
9. else if(number==50){
10. printf("number is equal to 50");
11. }
12. else if(number==100){

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

13. printf("number is equal to 100");


14. }
15. else{
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Programming Functions
A function is a block of code that performs a specific task. Dividing complex problem into small
components makes program easy to understand and use.

Types of functions in C programming


Depending on whether a function is defined by the user or already included in C
compilers, there are two types of functions in C programming

There are two types of functions in C programming:

 Standard library functions


 User defined functions

Standard library functions


The standard library functions are built-in functions in C programming to handle tasks
such as mathematical computations, I/O processing, string handling etc.

These functions are defined in the header file. When you include the header file, these
functions are available for use. For example:

The printf() is a standard library function to send formatted output to the screen
(display output on the screen). This function is defined in "stdio.h" header file.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all
these functions are available for use.

User-defined functions
As mentioned earlier, C allow programmers to define functions. Such functions created
by the user are called user-defined functions.

Depending upon the complexity and requirement of the program, you can create as
many user-defined functions as you want.

How user-defined function works?


#include <stdio.h>

void functionName()

... .. ...

... .. ...

int main()

... .. ...

... .. ...

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

functionName();

... .. ...

... .. ...

The execution of a C program begins from the main() function.

When the compiler encounters functionName(); inside the main function, control of the
program jumps to

void functionName()

And, the compiler starts executing the codes inside the user-defined function.

The control of the program jumps to statement next to functionName(); once all the
codes inside the function definition are executed.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

C Programming User-defined
functions

A function is a block of code that performs a specific task.

C allows you to define functions according to your need. These functions are known as
user-defined functions. For example:

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Suppose, you need to create a circle and color it depending upon the radius and color.
You can create two functions to solve this problem:

 createCircle() function
 color() function

Example: User-defined function


Here is a example to add two integers. To perform this task, a user-defined
function addNumbers() is defined.

#include <stdio.h>

int addNumbers(int a, int b); // function prototype

int main()
{
int n1,n2,sum;

printf("Enters two numbers: ");


scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call

printf("sum = %d",sum);

return 0;
}

int addNumbers(int a,int b) // function definition


{

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

int result;
result = a+b;
return result; // return statement
}

Function prototype
A function prototype is simply the declaration of a function that specifies function's
name, parameters and return type. It doesn't contain function body.

A function prototype gives information to the compiler that the function may later be
used in the program.

Syntax of function prototype


returnType functionName(type1 argument1, type2 argument2,...);

In the above example, int addNumbers(int a, int b); is the function prototype which
provides following information to the compiler:

1. name of the function is addNumbers()


2. return type of the function is int
3. two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before
the main() function.

Calling a function
Control of the program is transferred to the user-defined function by calling it.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Syntax of function call


functionName(argument1, argument2, ...);

In the above example, function call is made using addNumbers(n1,n2); statement inside
the main().

Function definition
Function definition contains the block of code to perform a specific task i.e. in this case,
adding two numbers and returning it.

Syntax of function definition


returnType functionName(type1 argument1, type2 argument2, ...)

//body of the function

When a function is called, the control of the program is transferred to the function
definition. And, the compiler starts executing the codes inside the body of a function.

Passing arguments to a function


In programming, argument refers to the variable passed to the function. In the above
example, two variables n1 and n2 are passed during function call.

The parameters a and b accepts the passed arguments in the function definition. These
arguments are called formal parameters of the function.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

The type of arguments passed to a function and the formal parameters must match,
otherwise the compiler throws error.

If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also
should be of float type.

A function can also be called without passing an argument.

Return Statement
The return statement terminates the execution of a function and returns a value to the
calling function. The program control is transferred to the calling function after return
statement.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

In the above example, the value of variable result is returned to the variable sum in
the main() function.

Syntax of return statement


return (expression);

For example,

return a;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

return (a+b);

The type of value returned from the function and the return type specified in function
prototype and function definition must match.

For better understanding of arguments and return value from the function, user-defined
functions can be categorized as:

 Function with no arguments and no return value


 Function with no arguments and a return value
 Function with arguments and no return value
 Function with arguments and a return value.

The 4 programs below check whether an integer entered by the user is a prime number
or not. And, all these programs generate the same output.

Example #1: No arguments passed and no


return Value
#include <stdio.h>

void checkPrimeNumber();

int main()
{
checkPrimeNumber(); // no argument is passed to prime()
return 0;
}

// return type of the function is void becuase no value is returned from


the function
void checkPrimeNumber()
{
int n, i, flag=0;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

printf("Enter a positive integer: ");


scanf("%d",&n);

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
{
flag = 1;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}

The checkPrimeNumber() function takes input from the user, checks whether it is a prime
number or not and displays it on the screen.

The empty parentheses in checkPrimeNumber(); statement inside the main() function


indicates that no argument is passed to the function.

The return type of the function is void. Hence, no value is returned from the function.

Example #2: No arguments passed but a


return value
#include <stdio.h>
int getInteger();

int main()
{
int n, i, flag = 0;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

// no argument is passed to the function


// the value returned from the function is assigned to n
n = getInteger();

for(i=2; i<=n/2; ++i)


{
if(n%i==0){
flag = 1;
break;
}
}

if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);

return 0;
}

// getInteger() function returns integer entered by the user


int getInteger()
{
int n;

printf("Enter a positive integer: ");


scanf("%d",&n);

return n;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

The empty parentheses in n = getInteger(); statement indicates that no argument is


passed to the function. And, the value returned from the function is assigned to n.

Here, the getInteger() function takes input from the user and returns it. The code to
check whether a number is prime or not is inside the main() function.

Example #3: Argument passed but no return


value
#include <stdio.h>
void checkPrimeAndDisplay(int n);

int main()
{
int n;

printf("Enter a positive integer: ");


scanf("%d",&n);

// n is passed to the function


checkPrimeAndDisplay(n);

return 0;
}

// void indicates that no value is returned from the function


void checkPrimeAndDisplay(int n)
{
int i, flag = 0;

for(i=2; i <= n/2; ++i)

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

{
if(n%i == 0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}

The integer value entered by the user is passed to checkPrimeAndDisplay() function.

Here, the checkPrimeAndDisplay() function checks whether the argument passed is a


prime number or not and displays the appropriate message.

Example #4: Argument passed and a return


value
#include <stdio.h>
int checkPrimeNumber(int n);

int main()
{
int n, flag;

printf("Enter a positive integer: ");


scanf("%d",&n);

// n is passed to the checkPrimeNumber() function


// the value returned from the function is assigned to flag variable

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

flag = checkPrimeNumber(n);

if(flag==1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);

return 0;
}

// integer is returned from the function


int checkPrimeNumber(int n)
{
/* Integer value is returned from function checkPrimeNumber() */
int i;

for(i=2; i <= n/2; ++i)


{
if(n%i == 0)
return 1;
}

return 0;
}

The input from the user is passed to checkPrimeNumber() function.

The checkPrimeNumber() function checks whether the passed argument is prime or not.
If the passed argument is a prime number, the function returns 0. If the passed
argument is a non-prime number, the function returns 1. The return value is assigned
to flag variable.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

C Switch Statement
The switch statement in C language is used to execute the code from multiple conditions. It
is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

Rules for switch statement in C language


1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement
found in switch case, all the cases will be executed after matching the case value. It is known
as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

1. int x,y,z;
2. char a,b;
3. float f;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

/************************************************************************
******

Online C Compiler.

Code, Compile, Run and Debug C program online.

Write your code in this editor and press "Run" button to compile and execute it.

*************************************************************************
******/

#include<stdio.h>

#include<conio.h>

int main()

int i=1,num1,num2;

int choice;

do

printf("*****select your
option*****\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n");

scanf("%d",&choice);

switch(choice)

case 1:

printf("\nenter a number");

scanf("%d",&num1);

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

printf("\nenter a number");

scanf("%d",&num2);

printf("addition is %d",num1+num2);

break;

case 2:

printf("\nenter a number");

scanf("%d",&num1);

printf("\nenter a number");

scanf("%d",&num2);

printf("addition is %d",num1-num2);

break;

case 3:

printf("\nenter a number");

scanf("%d",&num1);

printf("\nenter a number");

scanf("%d",&num2);

printf("addition is %d",num1*num2);

break;

case 4:

printf("\nenter a number");

scanf("%d",&num1);

printf("\nenter a number");

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

scanf("%d",&num2);

printf("addition is %d",num1/num2);

break;

default:

printf("wrong choice");

printf("\nDo you want to continue press 1 for continue or press 0 to exit");

scanf("%d",&i);

}while(i>=1);

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

C Loops
The loops in C language are used to execute a block of code or a part of the program several
times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?


Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C
1) It saves code.

2) It helps to traverse the elements of array

Types of C Loops
There are three types of loops in C language that is given below:

1. do while

2. while

3. for

do-while loop in C
It iterates the code until condition is false. Here, condition is given after the code. So at least
once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

1. do{

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

2. //code to be executed
3. }while(condition);

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

while loop in C
Like do while, it iterates the code until condition is false. Here, condition is given before the
code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

1. while(condition){
2. //code to be executed
3. }

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

for loop in C
Like while, it iterates the code until condition is false. Here, initialization, condition and
increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

do while example
There is given the simple program of c language do while loop where we are printing the table
of 1.

1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
Program to print table for the given number using do while loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. do{
7. printf("%d \n",(number*i));
8. i++;
9. }while(i<=10);
10. return 0;
11. }
Output
Enter a number: 5
5
10
15
20

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100

Example of while loop in C language


Let's see the simple program of while loop that prints table of 1.

1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10

Program to print table for the given number using


while loop in C
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0,b=9;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

4. printf("Enter a number: ");


5. scanf("%d",&number);
6. while(i<=10){
7. printf("%d \n",(number*i));
8. i++;
9. }
10. return 0;
11. }
Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000

C continue statement
The continue statement in C language is used to continue the execution of loop (while, do
while and for). It is used with if condition within the loop.

In case of inner loops, it continues the control of inner loop only.

Syntax:
1. jump-statement;
2. continue;

The jump statement can be while, do while and for loop.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Example of continue statement in c


1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
12. }
Output
1
2
3
4
6
7
8
9
10

As you can see, 5 is not printed on the console because loop is continued at i==5.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

C goto statement
The goto statement is known as jump statement in C language. It is used to unconditionally
jump to other label. It transfers control to other parts of the program.

It is rarely used today because it makes program less readable and complex.

Syntax:

1. goto label;

goto example
Let's see a simple example to use goto statement in C language.

1. #include <stdio.h>
2. int main() {
3. int age;
4. ineligible: //as a lable
5. printf("You are not eligible to vote!\n");
6.
7. printf("Enter you age:\n");
8. scanf("%d", &age);
9. if(age<18)
10. goto ineligible;
11. else
12. printf("You are eligible to vote!\n");
13.
14. return 0;
15. }

Output:

You are not eligible to vote!


Enter you age:
11
You are not eligible to vote!
Enter you age:
44
You are eligible to vote!

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Type Casting in C
Type casting allows us to convert one data type into other. In C language, we use cast
operator for type casting which is denoted by (type).

Syntax:

1. (type)value;

Note: It is always recommended to convert lower value to higher for avoiding data loss.

Without Type Casting:

1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2

With Type Casting:

1. float f=(float) 9/4;


2. printf("f : %f\n", f );//Output: 2.250000

Type Casting example


Let's see a simple example to cast int value into float.

1. #include<stdio.h>
2. int main(){
3. float f= (float)9/4;
4. printf("f : %f\n", f );
5. return 0;
6. }

Output:

f : 2.250000

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Recursion in C
When function is called within the same function, it is known as recursion in C. The function
which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail
recursion. In tail recursion, we generally call the same function with return statement. An
example of tail recursion is given below.

Let's see a simple example of recursion.

1. recursionfunction(){
2. recursionfunction();//calling self function
3. }

Example of tail recursion in C


Let's see an example to print factorial number using tail recursion in C language.

1. #include<stdio.h>
2. int factorial (int n)
3. {
4. if ( n < 0)
5. return -1; /*Wrong value*/
6. if (n == 0)
7. return 1; /*Terminating condition*/
8. return (n * factorial (n -1));
9. }
10. int main(){
11. int fact=0;
12. fact=factorial(5);
13. printf("\n factorial of 5 is %d",fact);
14. return 0;
15. }
Output
factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Storage Classes in C
Storage classes are used to define scope and life time of a variable. There are four storage
classes in C programming.

o auto

o extern

o static

o register

Storage Storage Default Scope Life-time


Classes Place Value

auto RAM Garbage Local Within function


Value

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

extern RAM Zero Global Till the end of main program, May
be declared anywhere in the
program

static RAM Zero Local Till the end of main program,


Retains value between multiple
functions call

register Register Garbage Local Within function


Value

1) auto
The auto keyword is applied to all local variables automatically. It is the default storage class
that is why it is known as automatic variable.

1. #include<stdio.h>
2. int main(){
3. int a=10;
4. auto int b=10;//same like above
5. printf("%d %d",a,b);
6. return 0;
7. }

Output:

10 10

2) register
The register variable allocates memory in register than RAM. Its size is same of register size.
It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

1. register int counter=0;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

3) static
The static variable is initialized only once and exists till the end of the program. It retains its
value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

1. #include<stdio.h>
2. int func(){
3.
4. static int i=0;//static variable
5. int j=0;//local variable
6. i++;
7. j++;
8. printf("i= %d and j= %d\n", i, j);
9. }
10. int main() {
11. func();
12. func();
13. func();
14. return 0;
15. }

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern
The extern variable is visible to all the programs. It is used if two or more files are sharing
same variable or function.

1. extern int counter=0;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

C Array
Array in C language is a collection or group of elements (data). All the elements of c array
are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks
of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to
manage. For example we can not access the value of these variables with only 1 or 2 lines of
code.

Another way to do this is array. By using array, we can access the elements easily. Only few
lines of code is required to access the elements of array.

Advantage of C Array
1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array
easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed
the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.

Declaration of C Array
We can declare an array in the c language in the following way.

1. data_type array_name[array_size];

Now, let us see the example to declare array.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

1. int marks[5];

Here, int is the data_type, marks is the array_name and 5 is the array_size.

Initialization of C Array
A simple way to initialize array is by index. Notice that array index starts from 0 and ends
with [SIZE - 1].

1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;

C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

10. //traversal of array


11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Output
80
60
70
85
75

C Array: Declaration with Initialization


We can initialize the c array at the time of declaration. Let's see the code.

1. int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define size. So it can also be written as the
following code.

1. int marks[]={20,30,40,50,60};

Let's see the full program to declare and initialize the array in C.

1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
60

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Two Dimensional Array in C


The two dimensional array in C language is represented in the form of rows and columns, also
known as matrix. It is also known as array of arrays or list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known
as multidimensional arrays.

Declaration of two dimensional Array in C


We can declare an array in the c language in the following way.

1. data_type array_name[size1][size2];

A simple example to declare two dimensional array is given below.

1. int twodimen[4][3];

Here, 4 is the row number and 3 is the column number.

Initialization of 2D Array in C
A way to initialize the two dimensional array at the time of declaration is given below.

1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Two dimensional array example in C


1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

C Pointers
The pointer in C language is a variable, it is also known as locator or indicator that points
to an address of a value.

Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer
There are many usage of pointers in c language.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

1) Dynamic memory allocation


In c language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.

2) Arrays, Functions and Structures


Pointers in c language are widely used in arrays, functions and structures. It reduces the code
and improves the performance.

Symbols used in pointer


Symbol Name Description

& (ampersand sign) address of operator determines the address of a variable.

* (asterisk sign) indirection operator accesses the value at the address.

Address Of Operator
The address of operator '&' returns the address of a variable. But, we need to use %u to
display the address of a variable.

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("value of number is %d, address of number is %u",number,&number);
5. return 0;
6. }
Output
value of number is 50, address of number is fff4

Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol).

1. int *a;//pointer to int


2. char *c;//pointer to char

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Pointer example
An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable
i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
return 0;
}

Output
Address of number variable is fff4
Address of p variable is fff4

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Value of p variable is 50

NULL Pointer
A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have
any address to be specified in the pointer at the time of declaration, you can assign NULL
value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

Pointer Program to swap 2 numbers without using


3rd variable
1. #include<stdio.h>
2. int main(){
3. int a=10,b=20,*p1=&a,*p2=&b;
4.
5. printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
6. *p1=*p1+*p2;
7. *p2=*p1-*p2;
8. *p1=*p1-*p2;
9. printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
10.
11. return 0;
12. }
Output
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

C Pointer to Pointer
In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the
address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

1. int **p2;

C pointer to pointer example


Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the
address of number variable (fff4).

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. int **p2;//pointer to pointer
6. p=&number;//stores the address of number variable
7. p2=&p;
8. printf("Address of number variable is %x \n",&number);

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

9. printf("Address of p variable is %x \n",p);


10. printf("Value of *p variable is %d \n",*p);
11. printf("Address of p2 variable is %x \n",p2);
12. printf("Value of **p2 variable is %d \n",*p);
13. return 0;
14. }
15.
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

C Strings
String in C language is an array of characters that is terminated by \0 (null character).

There are two ways to declare string in c language.

1. By char array

2. By string literal

Let's see the example of declaring string by char array in C language.

1. char ch[10]={‘s’, ’w’, ’a’, 't', ’I’, '\0'};

As you know well, array index starts from 0, so it will be represented as in the figure given
below.

While declaring string, size is not mandatory. So you can write the above code as given below:

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

1. char ch[]={‘s’, ’w’, ’a’, 't', ’I’, '\0'};

You can also define string by string literal in C language. For example:

1. char ch[]="swati";

In such case, '\0' will be appended at the end of string by the compiler.

Difference between char array and string literal


The only difference is that string literal cannot be changed whereas string declared by char
array can be changed.

String Example in C
Let's see a simple example to declare and print string. The '%s' is used to print string in c
language.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]={'s', 'w', 'a', 't', 'i', '\0'};
5. char ch2[11]="swati";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10. }

Output:

Char Array Value is: swati


String Literal Value is: swati

C gets() and puts() functions


The gets() function reads string from user and puts() function prints the string. Both functions
are defined in <stdio.h> header file.

Let's see a simple program to read and write string using gets() and puts() functions.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char name[50];
5. printf("Enter your name: ");
6. gets(name); //reads string from user
7. printf("Your name is: ");
8. puts(name); //displays string
9. return 0;
10. }

Output:

Enter your name: Sonoo Jaiswal


Your name is: Sonoo Jaiswal

C String Functions
There are many important string functions defined in "string.h" library.

No. Function Description

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, source) copies the contents of source string to destination


string.

3) strcat(first_string, concats or joins first string with second string. The


second_string) result of the string is stored in first string.

4) strcmp(first_string, compares the first string with second string. If both


second_string) strings are same, it returns 0.

5) strrev(string) returns reverse string.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

C String Length: strlen() function


The strlen() function returns the length of the given string. It doesn't count null character
'\0'.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]= {‘s’, ’w’, ’a’, 't', ’I’, '\0'}
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }

Output:

Length of string is: 5

C Copy String: strcpy()


The strcpy(destination, source) function copies the source string in destination.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
8. char ch[20]= {‘s’, ’w’, ’a’, 't', ’I’, '\0'};
4. char ch2[20];
5. strcpy(ch2,ch);
6. printf("Value of second string is: %s",ch2);
7. return 0;
8. }

Output:

Value of second string is: swati

C String Concatenation: strcat()

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

The strcat(first_string, second_string) function concatenates two strings and result is returned
to first_string.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }

Output:

Value of first string is: helloc

C Compare String: strcmp()


The strcmp(first_string, second_string) function compares two string and returns 0 if both
strings are equal.

Here, we are using gets() function which reads string from the console.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }

Output:

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal

C Reverse String: strrev()


The strrev(string) function returns reverse of the given string. Let's see a simple example of
strrev() function.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }

Output:

Enter string: SWAti


String is: SWAti
reverse String is: itaws

C String Lowercase: strlwr()


The strlwr(string) function returns string characters in lowercase. Let's see a simple example
of strlwr() function.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

8. printf("\nLower String is: %s",strlwr(str));


9. return 0;
10. }

Output:

Enter string: SWAti


String is: SWAti
Lower String is: swati

C String Uppercase: strupr()


The strupr(string) function returns string characters in uppercase. Let's see a simple example
of strupr() function.

1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10. }

Output:

Enter string: swati


String is: swati
Upper String is:SWATI

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

C Math
C Programming allows us to perform mathematical operations through the functions defined
in <math.h> header file. The <math.h> header file contains various methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor() etc.

C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.

No. Function Description

1) ceil(number) rounds up the given number. It returns the integer value which
is greater than or equal to given number.

2) floor(number) rounds down the given number. It returns the integer value
which is less than or equal to given number.

3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of given number.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

C Math Example
Let's see a simple example of math functions found in math.h header file.

1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
12. printf("\n%d",abs(-12));
13. return 0;
14. }

Output:

4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Structure in C
Structure in c language is a user defined datatype that allows you to hold different type of
elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in
it.

It is widely used to store student information, employee information, product information,


book information etc.

Defining structure
The struct keyword is used to define structure. Let's see the syntax to define structure in c.

1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };

Let's see the example to define structure for employee in c.

1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };

Here, struct is the keyword, employee is the tag name of


structure; id, name and salary are the members or fields of the structure. Let's understand
it by the diagram given below:

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Example

Declaring structure variable


We can declare variable for the structure, so that we can access the member of structure
easily. There are two ways to declare structure variable:

1. By struct keyword within main() function

2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared
within the main function.

1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };

Now write given code inside the main() function.

1. struct employee e1, e2;

2nd way:

Let's see another way to declare variable at the time of defining structure.

1. struct employee
2. { int id;
3. char name[50];

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

4. float salary;
5. }e1,e2;
Which approach is good
But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the
structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main()
fuction.

Accessing members of structure


There are two ways to access structure members:

1. By . (member or dot operator)

2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

1. p1.id

C Structure example

Example of Structure in C
#include <stdio.h>
/* Created a structure here. The name of the structure is
* StudentData.
*/
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{
/* student is the variable of structure StudentData*/
struct StudentData student;

/*Assigning the values of each struct member here*/


student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

/* Displaying the values of struct members */


printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
return 0;
}
Output:

Student Name is: Steve


Student Id is: 1234
Student Age is: 30

Unions are quite similar to structures in C. Like structures, unions are also derived
types.

union car

char name[50];

int price;

};

Defining a union is as easy as replacing the keyword struct with the keyword union.

How to create union variables?


Union variables can be created in similar manner as structure variables.

union car

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

char name[50];

int price;

} car1, car2, *car3;

OR

union car

char name[50];

int price;

};

int main()

union car car1, car2, *car3;

return 0;

In both cases, union variables car1, car2 and union pointer variable car3 of type union
car is created.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Accessing members of a union


Again, the member of unions can be accessed in similar manner as structures.

In the above example, suppose you want to access price for union variable car1, it can
be accessed as:

car1.price

Likewise, if you want to access price for the union pointer variable car3, it can be
accessed as:

(*car3).price

or;

car3->price

Difference between union and structure


Though unions are similar to structure in so many ways, the difference between them is
crucial to understand.

The primary difference can be demonstrated by this example:

#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

} uJob;

struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;

int main()
{
printf("size of union = %d", sizeof(uJob));
printf("\nsize of structure = %d", sizeof(sJob));
return 0;
}

Output

size of union = 32

size of structure = 40

More memory is allocated to structures than union


As seen in the above example, there is a difference in memory allocation between union
and structure.

The amount of memory required to store a structure variable is the sum of memory size
of all members.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

But, the memory required to store a union variable is the memory required for the
largest element of an union.

Only one union member can be accessed at a time


In the case of structure, all of its members can be accessed at any time.

But, in the case of union, only one of its members can be accessed at a time and all
other members will contain garbage values.

#include <stdio.h>
union job
{
char name[32];
float salary;
int workerNo;
} job1;

int main()
{
printf("Enter name:\n");
scanf("%s", &job1.name);

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

printf("Enter salary: \n");


scanf("%f", &job1.salary);

printf("Displaying\nName :%s\n", job1.name);


printf("Salary: %.1f", job1.salary);

return 0;
}

Output

Enter name

Hillary

Enter salary

1234.23

Displaying

Name: f%Bary

Salary: 1234.2

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

SQL

What is SQL
o SQL stands for Structured Query Language.

o It is designed for managing data in a relational database management system


(RDBMS).

o It is pronounced as S-Q-L or sometime See-Qwell.

o SQL is a database language, it is used for database creation, deletion, fetching rows
and modifying rows etc.

o SQL is based on relational algebra and tuple relational calculus.

All DBMS like MySQL, Oracle, MS Access, Sybase, Informix, Postgres and SQL Server use SQL
as standard database language.

Why SQL is required


SQL is required:

o To create new databases, tables and views

o To insert records in a database

o To update records in a database

o To delete records from a database

o To retrieve data from a database

What SQL does


o With SQL, we can query our database in a numbers of ways, using English-like
statements.

o With SQL, user can access data from relational database management system.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

o It allows user to describe the data.

o It allows user to define the data in database and manipulate it when needed.

o It allows user to create and drop database and table.

o It allows user to create view, stored procedure, function in a database.

o It allows user to set permission on tables, procedure and view.

What is Database
A database is an organized collection of data.

Database handlers create database in such a way that only one set of software program
provide access of data to all the users.

The main purpose of database is to operate large amount of information by storing,


retrieving and managing.

There are many dynamic websites on the world wide web now a days which are handled
through databases. For example, a model to checks the availability of rooms in a hotel. It is
an example of dynamic website that uses database.

There are many database available like MySQL, Sybase, Oracle, Mango DB, Informix,
Postgre, SQL Server etc.

SQL or Structured Query Language is used to perform operation on the data stored in a
database. SQL depends on relational algebra and tuple relational calculus.

A cylindrical structure is used to display the image of a database.

What is RDBMS
RDBMS stands for Relational Database Management Systems..

All modern database management systems like SQL, MS SQL Server, IBM DB2, ORACLE, My-
SQL and Microsoft Access are based on RDBMS.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

It is called Relational Data Base Management System (RDBMS) because it is based on


relational model introduced by E.F. Codd.

How it works
Data is represented in terms of tuples (rows) in RDBMS.

Relational database is most commonly used database. It contains number of tables and each
table has its own primary key.

Due to a collection of organized set of tables, data can be accessed easily in RDBMS.

Brief History of RDBMS


During 1970 to 1972, E.F. Codd published a paper to propose the use of relational database
model.

RDBMS is originally based on that E.F. Codd's relational model invention.

What is table
The RDBMS database uses tables to store data. A table is a collection of related data entries
and contains rows and columns to store data.

A table is the simplest example of data storage in RDBMS.

Let's see the example of student table.

ID Name AGE C

1 Ajeet 24

2 aryan 20

3 Mahesh 21

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

4 Ratan 22

5 Vimal 26

What is field
Field is a smaller entity of the table which contains specific information about every record in
the table. In the above example, the field in the student table consist of id, name, age, course.

What is row or record


A row of a table is also called record. It contains the specific information of each individual
entry in the table. It is a horizontal entity in the table. For example: The above table contains
5 records.

Let's see one record/row in the table.

1 Ajeet 24 B

What is column
A column is a vertical entity in the table which contains all information associated with a
specific field in a table. For example: "name" is a column in the above table which contains
all information about student's name.

Ajeet

Aryan

Mahesh

Ratan

Vimal

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

NULL Values
The NULL value of the table specifies that the field has been left blank during record creation.
It is totally different from the value filled with zero or a field that contains space.

Data Integrity
There are the following categories of data integrity exist with each RDBMS:

Entity integrity: It specifies that there should be no duplicate rows in a table.

Domain integrity: It enforces valid entries for a given column by restricting the type, the
format, or the range of values.

Referential integrity: It specifies that rows cannot be deleted, which are used by other
records.

User-defined integrity: It enforces some specific business rules that are defined by users.
These rules are different from entity, domain or referential integrity.

SQL Syntax
SQL follows some unique set of rules and guidelines called syntax. Here, we are providing all
the basic SQL syntax.

o SQL is not case sensitive. Generally SQL keywords are written in uppercase.

o SQL statements are dependent on text lines. We can place a single SQL statement on
one or multiple text lines.

o You can perform most of the action in a database with SQL statements.

o SQL depends on relational algebra and tuple relational calculus.

SQL statement
SQL statements are started with any of the SQL commands/keywords like SELECT, INSERT,
UPDATE, DELETE, ALTER, DROP etc. and the statement ends with a semicolon (;).

Example of SQL statement:

1. SELECT "column_name" FROM "table_name";

Why semicolon is used after SQL statements:

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Semicolon is used to separate SQL statements. It is a standard way to separate SQL


statements in a database system in which more than one SQL statements are used in the
same call.

In this tutorial, we will use semicolon at the end of each SQL statement.

SQL Commands
These are the some important SQL command:

SELECT: it extracts data from a database.

UPDATE: it updates data in database.

DELETE: it deletes data from database.

CREATE TABLE: it creates a new table.

ALTER TABLE: it is used to modify the table.

DROP TABLE: it deletes a table.

CREATE DATABASE: it creates a new database.

ALTER DATABASE: It is used to modify a database.

INSERT INTO: it inserts new data into a database.

CREATE INDEX: it is used to create an index (search key).

DROP INDEX: it deletes an index.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

SQL Data Types

These are the general data types in SQL.

Data-type Syntax Explanation

Integer INTEGER The integer data type is used to specify an


integer value.

Smallint SMALLINT The smallint data type is used to specify


small integer value.

Numeric NUMERIC(P,S) It specifies a numeric value. Here 'p' is


precision value and 's' is scale value.

Real REAL The real integer is used to specify a single


precision floating point number.

Decimal DECIMAL(P,S) It specifies a decimal value. Here 'p' is


precision value and 's' is scale value.

Double precision DOUBLE It specifies double precision floating point


PRECISION number.

Float FLOAT(P) It specifies floating-point value e.g. 12.3,


4.5 etc. Here, 'p' is precision value.

Character CHAR(X) Here, 'x' is the character's number to


store.

Character VARCHAR2(X) Here, 'x' is the character's number to store


varying

Bit BIT(X) Here, 'x' is the number of bits to store

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Bit varying BIT VARYING(X) Here, 'x' is the number of bits to store
(length can vary up to x).

Date DATE It stores year, month and days values.

Time TIME It stores hour, minute and second values

Timestamp TIMESTAMP The timestamp data type is used to store


year, month, day, hour, minute and
second values.

Time with time TIME WITH TIME It is exactly same as time but also store
zone ZONE an offset from UTC of the time specified.

Timestamp with TIMESTAMP with It is same as timestamp but also stores an


time zone TIME ZONE offset from UTC of the time specified.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

SQL CREATE Database


The SQL CREATE DATABASE statement is used by a developer to create a database.

Let's see the syntax of SQL CREATE DATABASE:

1. CREATE DATABASE database_name;

If you want to add tables in that database, you can use CREATE TABLE statement.

Create Database in MySQL


In MySQL, same command is used to create a database.

1. CREATE DATABASE database_name;

Create Database in Oracle


You don't need to create database in Oracle. In Oracle database, you can create tables directly

SQL DROP Database


SQL DROP statement is used to delete or remove indexes from a table in the database.

If you want to delete or drop an existing database in a SQL schema, you can use SQL DROP
DATABASE

Let's see the syntax of SQL DROP DATABASE:

1. DROP DATABASE database_name;

If you delete or drop the database, all the tables and views will also be deleted. So be careful while
using this command

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

SQL RENAME Database


SQL RENAME DATABASE is used when you need to change the name of your database.
Sometimes it is used because you think that the original name is not more relevant to the
database or you want to give a temporary name to that database.

Let's see how to rename MySql and SQL Server databases.

Rename MySQL database


To rename the mysql database, you need to follow the following syntax:

1. RENAME DATABASE old_db_name TO new_db_name;

Rename SQL server database using T-SQL


This command is useful for SQL server 2005, 2008, 2008R2 and 2012.

1. ALTER DATABASE old_name MODIFY NAME = new_name

If you are using SQL server 2000, you can also use this command to rename the database.
But, Microsoft phased out it.

1. EXEC sp_renamedb 'old_name' , 'new_name'

SQL SELECT Database


In MySQL database, you need to select a database first before executing any query on table,
view etc. To do so, we use following query:

1. USE DATABASE database_name;

In oracle, you don't need to select database.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

SQL Table
Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is
known as relation and row as tuple.

Note: A table has a specified number of columns, but can have any number of rows.

Table is the simple form of data storage. A table is also considered as a convenient
representation of relations.

Let's see an example of an employee table:

Employee

EMP_NAME ADDRESS SALARY

Ankit Lucknow 15000

Raman Allahabad 18000

Mike New York 20000

In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS" and "SALARY"
are the column names. The combination of data of multiple columns forms a row e.g. "Ankit",
"Lucknow" and 15000 are the data of one row.

SQL TABLE Variable


The SQL Table variable is used to create, modify, rename, copy and delete tables. Table
variable was introduced by Microsoft.

It was introduced with SQL server 2000 to be an alternative of temporary tables.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

It is a variable where we temporary store records and results. This is same like temp table
but in the case of temp table we need to explicitly drop it.

Table variables are used to store a set of records. So declaration syntax generally looks like
CREATE TABLE syntax.

1. create table "tablename"


2. ("column1" "data type",
3. "column2" "data type",
4. ...
5. "columnN" "data type");

When a transaction rolled back the data associated with table variable is not rolled back.

A table variable generally uses lesser resources than a temporary variable.

Table variable cannot be used as an input or an output parameter.

SQL CREATE TABLE


SQL CREATE TABLE statement is used to create table in a database.

If you want to create a table, you should name the table and define its column and each
column's data type.

Let's see the simple syntax to create the table.

1. create table "tablename"


2. ("column1" "data type",
3. "column2" "data type",
4. "column3" "data type",
5. ...
6. "columnN" "data type");

The data type of the columns may vary from one database to another. For example, NUMBER
is supported in Oracle database for integer value whereas INT is supported in MySQL.

Let us take an example to create a STUDENTS table with ID as primary key and NOT NULL
are the constraint showing that these fields cannot be NULL while creating records in the
table.

1. SQL> CREATE TABLE STUDENTS (

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

2. ID INT NOT NULL,


3. NAME VARCHAR (20) NOT NULL,
4. AGE INT NOT NULL,
5. ADDRESS CHAR (25),
6. PRIMARY KEY (ID)
7. );

You can verify it, if you have created the table successfully by looking at the message
displayed by the SQL Server, else you can use DESC command as follows:

SQL> DESC STUDENTS;

FIELD TYPE NULL KEY DEFAULT EXTRA

ID Int(11) NO PRI

NAME Varchar(20) NO

AGE Int(11) NO

ADDRESS Varchar(25) YES NULL

4 rows in set (0.00 sec)

Now you have the STUDENTS table available in your database and you can use to store
required information related to students.

SQL CREATE TABLE Example in MySQL


Let's see the command to create a table in MySQL database.

1. CREATE TABLE Employee


2. (
3. EmployeeID int,
4. FirstName varchar(255),
5. LastName varchar(255),

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

6. Email varchar(255),
7. AddressLine varchar(255),
8. City varchar(255)
9. );

SQL CREATE TABLE Example in Oracle


Let's see the command to create a table in Oracle database.

1. CREATE TABLE Employee


2. (
3. EmployeeID number(10),
4. FirstName varchar2(255),
5. LastName varchar2(255),
6. Email varchar2(255),
7. AddressLine varchar2(255),
8. City varchar2(255)
9. );

SQL CREATE TABLE Example in Microsoft


SQLServer
Let's see the command to create a table in SQLServer database. It is same as MySQL and
Oracle.

1. CREATE TABLE Employee


2. (
3. EmployeeID int,
4. FirstName varchar(255),
5. LastName varchar(255),
6. Email varchar(255),
7. AddressLine varchar(255),
8. City varchar(255)
9. );

SQL DROP TABLE

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

A SQL DROP TABLE statement is used to delete a table definition and all data from a table.

This is very important to know that once a table is deleted all the information available in the
table is lost forever, so we have to be very careful when using this command.

Let's see the syntax to drop the table from the database.

1. DROP TABLE "table_name";

Let us take an example:

First we verify STUDENTS table and then we would delete it from the database.

1. SQL> DESC STUDENTS;

FIELD TYPE NULL KEY

ID Int(11) NO PRI

NAME Varchar(20) NO

AGE Int(11) NO

ADDRESS Varchar(25) YES

1. 4 rows in set (0.00 sec)

This shows that STUDENTS table is available in the database, so we can drop it as follows:

1. SQL>DROP TABLE STUDENTS;

Now, use the following command to check whether table exists or not.

1. SQL> DESC STUDENTS;


1. Query OK, 0 rows affected (0.01 sec)

As you can see, table is dropped so it doesn't display it.

SQL DROP TABLE Example in MySQL


Let's see the command to drop a table from the MySQL database.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

1. DROP TABLE table_name;

SQL DROP TABLE Example in Oracle


Let's see the command to drop a table from Oracle database. It is same as MySQL.

1. DROP TABLE table_name;

SQL DROP TABLE Example in Microsoft SQLServer


Let's see the command to drop a table from SQLServer database. It is same as MySQL.

1. DROP TABLE table_name;

SQL DELETE TABLE


The DELETE statement is used to delete rows from a table. If you want to remove a specific
row from a table you should use WHERE condition.

1. DELETE FROM table_name [WHERE condition];

But if you do not specify the WHERE condition it will remove all the rows from the table.

1. DELETE FROM table_name;

There are some more terms similar to DELETE statement like as DROP statement and
TRUNCATE statement but they are not exactly same there are some differences between
them.

Difference between DELETE and TRUNCATE statements


There is a slight difference b/w delete and truncate statement. The DELETE statement only
deletes the rows from the table based on the condition defined by WHERE clause or delete all
the rows from the table when condition is not specified.

But it does not free the space containing by the table.

The TRUNCATE statement: it is used to delete all the rows from the table and free the
containing space.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

Let's see an "employee" table.

Emp_id Name Address

1 Aryan Allahabad

2 Shurabhi Varanasi

3 Pappu Delhi

Execute the following query to truncate the table:

1. TRUNCATE TABLE employee;

Difference b/w DROP and TRUNCATE statements


When you use the drop statement it deletes the table's row together with the table's definition
so all the relationships of that table with other tables will no longer be valid.

When you drop a table:

o Table structure will be dropped

o Relationship will be dropped

o Integrity constraints will be dropped

o Access privileges will also be dropped

On the other hand when we TRUNCATE a table, the table structure remains the same, so
you will not face any of the above problems.

SQL RENAME TABLE


SQL RENAME TABLE syntax is used to change the name of a table. Sometimes, we choose
non-meaningful name for the table. So it is required to be changed.

Let's see the syntax to rename a table from the database.

1. ALTER TABLE table_name

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

2. RENAME TO new_table_name;

Optionally, you can write following command to rename the table.

1. RENAME old_table _name To new_table_name;

Let us take an example of a table named "STUDENTS", now due to some reason we want to
change it into table name "ARTISTS".

Table1: students

Name Age City

Amrita gill 25 Amritsar

Amrender sirohi 22 Ghaziabad

Divya khosla 20 Delhi

You should use any one of the following syntax to RENAME the table name:

1. ALTER TABLE STUDENTS


2. RENAME TO ARTISTS;

Or

1. RENAME STUDENTS TO ARTISTS;


2. After that the table "students" will be changed into table name "artists"

SQL TRUNCATE TABLE


A truncate SQL statement is used to remove all rows (complete data) from a table. It is similar
to the DELETE statement with no WHERE clause.

TRUNCATE TABLE Vs DELETE TABLE


Truncate table is faster and uses lesser resources than DELETE TABLE command.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

TRUNCATE TABLE Vs DROP TABLE


Drop table command can also be used to delete complete table but it deletes table structure
too. TRUNCATE TABLE doesn't delete the structure of the table.

Let's see the syntax to truncate the table from the database.

1. TRUNCATE TABLE table_name;

For example, you can write following command to truncate the data of employee table

1. TRUNCATE TABLE Employee;

Note: The rollback process is not possible after truncate table statement. Once you truncate
a table you cannot use a flashback table statement to retrieve the content of the table.

SQL COPY TABLE


If you want to copy a SQL table into another table in the same SQL server database, it is
possible by using the select statement.

The syntax of copying table from one to another is given below:

1. SELECT * INTO <destination_table> FROM <source_table>

For example, you can write following command to copy the records of hr_employee table into
employee table.

1. SELECT * INTO admin_employee FROM hr_employee;

Note: SELECT INTO is totally different from INSERT INTO statement.

SQL ALTER TABLE


The ALTER TABLE statement is used to add, modify or delete columns in an existing table. It
is also used to rename a table.

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

You can also use SQL ALTER TABLE command to add and drop various constraints on an
existing table.

SQL ALTER TABLE Add Column


If you want to add columns in SQL table, the SQL alter table syntax is given below:

1. ALTER TABLE table_name ADD column_name column-definition;

If you want to add multiple columns in table, the SQL table will be

1. ALTER TABLE table_name


2. ADD (column_1 column-definition,
3. column_2 column-definition,
4. .....
5. column_n column-definition);

SQL ALTER TABLE Modify Column


If you want to modify an existing column in SQL table, syntax is given below:

1. ALTER TABLE table_name MODIFY column_name column_type;

If you want to modify multiple columns in table, the SQL table will be

1. ALTER TABLE table_name


2. MODIFY (column_1 column_type,
3. column_2 column_type,
4. .....
5. column_n column_type);

SQL ALTER TABLE DROP Column


The syntax of alter table drop column is given below:

1. ALTER TABLE table_name DROP COLUMN column_name;

www.cryolitesoftwares.com contact:0522-4962150
Cryolite India Softwares Pvt. Ltd. C Programming Language Notes

SQL ALTER TABLE RENAME Column


The syntax of alter table rename column is given below:

1. ALTER TABLE table_name


2. RENAME COLUMN old_name to new_name;

1300000
-250000
10,50,000
-2,50,000*5%=12,500
800000
-500000*20%=100000
300000*30%=90000

www.cryolitesoftwares.com contact:0522-4962150

Das könnte Ihnen auch gefallen