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

C Language Notes

The document discusses the history and features of the C programming language. It describes how C was developed in the 1970s and influenced by other languages. The key parts of a C program are defined including headers, functions, variables, statements, and comments. Different data types are outlined along with their sizes and ranges. Common operators used in C like arithmetic, relational, and logical operators are also explained.

Uploaded by

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

C Language Notes

The document discusses the history and features of the C programming language. It describes how C was developed in the 1970s and influenced by other languages. The key parts of a C program are defined including headers, functions, variables, statements, and comments. Different data types are outlined along with their sizes and ranges. Common operators used in C like arithmetic, relational, and logical operators are also explained.

Uploaded by

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

*

-By kanhaiya lal kumawat


History of „c‟ language

 „c‟ language is an structure programming language

 „c‟ language is developed by Dennis Ritchie in 1972 at bell Laboratories in U.S.A.

 „c‟ language is developed using three different languages- ALGOL, BCPL and B
Language.

 „c‟ language uses many concepts from these languages while introduced many new
concepts such as data types, struct, pointer etc.

 After developed „c‟ language the first operating system made by it is UNIX.
Versions of „c‟ language

2
Features of „c‟ language
First „c‟ program
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
/* my first „c‟ program */
printf(“hello all please stay at your home when corona is live”);
getch();
}

Different parts of C program


 Pre-processor #include
 Header file stdio.h,conio.h
 Function main(),clrscr(),getch(),printf.
 Variables a=5, here a is an variable
 Statements & expressions c=a+b; is an statement
 Comments /* -----*/ is an comment
*

-by kanhaiya lal kumawat


Tokens in C

Tokens are the smallest individual unit of a program, which are meaningful to the
compiler. The following are the types of tokens: Keywords, Identifiers, Constant,
Strings, Operators, etc.

Keywords :
Keywords are predefined, reserved words in C language. They have special
meaning to the compilers. There are total 32 keywords in C.
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned
Identifiers :
Each program element in C programming is known as an identifier. They are
used for naming of variables, functions, array etc. These are user-defined names
Which consist of alphabets, number, underscore „_‟. Identifier‟s name should not be
sameor same as keywords. Keywords are not used as identifiers.

Rules for naming C identifiers −


 It must begin with alphabets or underscore.
 Only alphabets, numbers, underscore can be used, no other special
characters, punctuations are allowed.
 It must not contain white-space.
 It should not be a keyword.
 It should be up to 31 characters long.
Strings
A string is an array of characters ended with a null character(\0). This null character
indicates that string has ended. Strings are always enclosed with double quotes(“ “).
Let us see how to declare String in C language −
char string[20] = {„s‟,‟t‟,‟u‟,‟d‟,‟y‟, „\0‟};
char string[20] = “demo”;
char string [] = “demo”;

Char name=“kanahiya”;
*
-by kanhaiya lal kumawat
Data types
Data types specify how we enter data into our programs and what type of
data we enter. C language has some predefined set of data types to handle
various kinds of data that we can use in our program. These data types have
different storage capacities.

C language supports 2 different type of data types:

1. Primary data types:


These are fundamental data types in C namely
integer(int), floating point(float), character(char) and void.

2. Derived data types:


Derived data types are nothing but primary
datatypes but a little twisted or grouped together like array, stucture, union
and pointer. These are discussed in details later.
Data type Size in bytes Range
Char or signed char 1 -128 to 127

Unsigned char 1 0 to 255


int or signed int 2 -32768 to 32767
Unsigned int 2 0 to 65535
Short int or Unsigned short 2 0 to 255
int

Signed short int 2 -128 to 127


Long int or Signed long int 4 -2147483648 to 2147483647

Unsigned long int 4 0 to 4294967295


float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308

Long double 10 3.4E-4932 to 1.1E+4932


#include<stdio.h> #include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h> #include<conio.h>
Void main() Void main() Void main()
{ { {
Int a=5; float rate=5.5; char alpha=„A‟;
Clrscr(); Clrscr(); Clrscr();
printf(“%d”,a); printf(“%f”,rate); printf(“%c”,alpha);
getch(); getch(); getch();
} } }
Result : 5 Result : 5.5 Result : A
Use of scanf function :

#include<stdio.h> #include<stdio.h> #include<stdio.h>


#include<conio.h> #include<conio.h> #include<conio.h>
Void main() Void main() Void main()
{ { {
Int a; Int a,b; Int a,b;
clrscr(); clrscr(); clrscr();
printf(“enter a number”); printf(“enter first number”); printf(“enter two numbers”);
Scanf(“%d”,&a); Scanf(“%d”,&a); Scanf(“%d%d”,&a,&b);
printf(“%d”,a); Printf(“enter second number”); Printf(“%d%d”,a,b);
getch(); Scanf(“%d”&b); getch();
} Printf(“%d%d”,a,b); }
getch();
}
*
-by kanhaiya lal kumawat
Operator
An operator is a symbol that tells the compiler to perform a certain mathematical
or logical manipulation. Operators are used in programs to manipulate data and
variables.

C operators can be classified into following types:


 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Assignment operators
 Conditional operators
 Special operators
Arithmetic operators :
C supports all the basic arithmetic operators. The following
table shows all the basic arithmetic operators.

Operator Description
+ adds two operands
- subtract second operands from first

* multiply two operand


/ divide numerator by denominator

% remainder of division
++ Increment operator - increases integer
value by one

-- Decrement operator - decreases


integer value by one
Example 1:
#include<stdio.h> Note : when all arithmetic operators are
#include<conio.h> present in an single expression then solving
Void main() order is like that-
{ first *,/,%
Int a,b; after it +,-
clrscr(); Example :
printf(“enter two numbers”);
scanf(“%d%d”,&a,&b); Int A=5, b=10, c=7,d;
printf(“%d”,a+b);
getch(); d=a*b+c/a-4%3*2;
} D=5*10+7/5-4%3*2; // *
d=50+7/5-4%3*2; // /
Example 2: D=50+1-4%3*2; // %
#include<stdio.h> d=50+1-1*2; // *
#include<conio.h> D=50+1-2; // +
Void main() D=51-2; // -
{ D=49;
Int a,b;
clrscr();
printf(“enter two numbers”);
scanf(“%d%d”,&a,&b);
printf(“%d%d”,a++,++b);
getch();
}
Relational operators :
Result of relational operator is always in true(1) and false(0). The
following table shows all relation operators supported by C.

Operator Description
== 4==7 false Check if two operand are equal

!= 4!=7 true Check if two operand are not equal.

> 4>7 false Check if operand on the left is greater


than operand on the right

< 4<7 true Check operand on the left is smaller


than right operand
>= 4>=7 false check left operand is greater than or
equal to right operand

<= 4<=7 true Check if operand on left is smaller


than or equal to right operand
Logical operators :
C language supports following 3 logical operators. When user want to
Take decision between more than one conditions than logical operators are used.

operator Description

&& Logical AND


|| Logical OR
! Logical NOT

Logical and :
A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1
Logical OR :
A B A||B
0 0 0
0 1 1
1 0 1
1 1 1

Logical Not :
A !(A)
0 1
1 0
Example of AND operator : #include<stdio.h>
int a=7, b=10, c; #include<conio.h>
c= (a==b) && (a<b); Void main()
c= 0 && 1 {
c=0 Int a=7,b=10,c;
c=(a==b)&&(a<b);
Example of OR operator : printf(“%d”,c);
int a=7, b=10, c; getch();
c= (a==b) || (a<b); }
c= 0||1
c= 1

Example of NOT operator :


int a=7, b=10, c;
c= !(a==b);
c=!(0)
c=1
Bitwise operator
Bitwise operator perform operation at bit level. So first we need to calculate binary
of the given numbers and after it we can perform operations.

Types of bitwise operators :


1. Bitwise AND(&)
2. Bitwise OR(|)
3. Bitwise XOR(^)
4. Bitwise right shift(>>)
5. Bitwise left shift(<<)

1. Bitwise AND(&) :
A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1

Operation is same as logical AND operator, but on two numbers not condition.
Eaxmple 1: Eaxmple 2:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
Int a=45,b=90,c; Int a,b,c;
clrscr(); clrscr();
c=a&b; printf(“enter two numbers”);
printf(“%d”,c); scanf(“%d%d”,&a,&b);
getch(); c=a&b;
} printf(“%d”,c);
getch();
}

How to solve it :
we have a=45, b=90;
First we need to calculate binary of 45 and 90.
512 256 128 64 32 16 8 4 2 1
a= 0 1 0 1 1 0 1
b= 1 0 1 1 0 1 0
& -------------------------
0 0 0 1 0 0 0
2. Bitwise OR(|) :

A B A||B
0 0 0
0 1 1
1 0 1
1 1 1

Eaxmple 1: How to solve it :


#include<stdio.h> we have a=45, b=90;
#include<conio.h> First we need to calculate binary of 45 and 90.
void main() 512 256 128 64 32 16 8 4 2 1
{ a= 0 1 0 1 1 0 1
Int a=45,b=90,c; b= 1 0 1 1 0 1 0
clrscr(); | -------------------------
c=a|b; 1 1 1 1 1 1 1
printf(“%d”,c);
getch();
}
3. Bitwise XOR(^) :

A B A||B
0 0 0
0 1 1
1 0 1
1 1 0

Eaxmple 1: How to solve it :


#include<stdio.h> we have a=45, b=90;
#include<conio.h> First we need to calculate binary of 45 and 90.
void main() 512 256 128 64 32 16 8 4 2 1
{ a= 0 1 0 1 1 0 1
Int a=45,b=90,c; b= 1 0 1 1 0 1 0
clrscr(); ^ -------------------------
c=a^b; 1 1 1 0 1 1 1
printf(“%d”,c);
getch();
}
4. Bitwise right shift(>>) :
bitwise right shift operator is used for shifting number of bits
on the right side. In this operator we need an number and how much bits for shifting
On right side.
Example :
How to solve it : 16 bit register
#include<stdio.h>
#include<conio.h> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
void main()
Suppose number is a=49 so first calculate binary :
{
64 32 16 8 4 2 1
Int a,b,c;
a= 1 1 0 0 0 1
clrscr();
And shifting of bits is 3 because maximum bits we can shift
printf(“enter an number”);
Are 16.
scanf(“%d”,&a);
printf(“enter number of shifting bits”);
Scanf(“%d”,&b);
c=a>>b; Binary put on the register :
printf(“%d”,c);
0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1
getch();
}
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0

6
5. Bitwise left shift(<<) :
bitwise left shift operator is used for shifting number of bits
on the left side. In this operator we need an number and how much bits for shifting
On left side.
Example : How to solve it : 16 bit register
#include<stdio.h> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#include<conio.h>
void main() Suppose number is a=49 so first calculate binary :
{ 64 32 16 8 4 2 1
Int a,b,c; a= 1 1 0 0 0 1
clrscr(); And shifting of bits is 2 because maximum bits we can shift
printf(“enter an number”); Are 16.
scanf(“%d”,&a);
printf(“enter number of shifting bits”);
Scanf(“%d”,&b);
c=a<<b; Binary put on the register :
printf(“%d”,c); 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1
getch(); 128 64 32 16 8 4 2 1
} 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0
At the last 2
0 bit autometic
Result : 196 added
Assignment operators

In this type of operators always right hand side variable‟s value assigned into left side
Variable with the different different operators.

Types of assignment operators :

Operators expression Solving process


= a=b; a=b;
+= a+=b a=a+b;
-= a-=b a=a-b;
*= a*=b a=a*b;
/= a/=b a=a/b;
%= a%=b a=a%b;
Eaxmple :
#include<stdio.h>
#include<conio.h>
void main()
{
Int a,b;
clrscr();
printf(“enter two numbers”);
scanf(“%d%d”,&a,&b);
a=b;
printf(“%d”,a);
getch();
}
Result: value of b
6. Conditional operator :
it is also know an ternary operator and ?: operator.
Syntax :
condition ? True part : false part;

In this operator we have an condition if the condition is true the true part executed
otherwise false part is executed.

Example :
Program for check a number is even or odd.
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf(“enter a number”);
scanf(“%d”,&a);
(a%2==0) ? printf(“number is even”) : printf(“number is odd”);
getch();
}
Program for check a greater number between two numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“enter two number”);
scanf(“%d%d”,&a,&b);
(a>b) ? printf(“a is greater”) : printf(“b is greater”);
getch();
}
7. Special operators :
a. address of(&)
b. sizeof
c. pointer

a. Address of(&) :
address of operator is used for finding address of the variable in
Computer memory.
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf(“enter a number”);
scanf(“%d”,&a);
printf(“%d”,a); // value of a
printf(“%d”,&a); // find address of variable a
getch();
}
b. sizeof operator :
using sizeof operator we can find size of the variable in c program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf(“enter a number”);
scanf(“%d”,&a);
Note : when in an expression any type of
printf(“%d”,a);
variables are present then we choose
printf(“%d”,sizeof(a));
always maximum size variable.
getch();
}
sizeof(5+5.7+4) // 4
int A=2
sizeof(A) // 2
float A=2.2 //4
sizeof(A) // 1
char a=„m‟
sizeof(a)
Operators Precedence in C
Category Operator Associativity

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

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


*
-by kanhaiya lal kumawat
Decision making is about deciding the order of execution of statements based on certain
conditions or repeat a group of statements until certain specified conditions are met.
C language handles decision-making by supporting the following statements,
1. if statement
2. If-else statement
3. If-else if-else statement
4. Nested if statement
5. switch statement
6. conditional operator statement (? : operator)

1. If statement :
if statement is the most simple decision making statement. It is used
to decide whether a certain statement or block of statements will be executed or not
i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax:
if(condition)
{ // Statements to execute if
// condition is true
}
Example 1 : Example 2 :
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
Int a; Int a,b;
clrscr(); clrscr();
printf(“enter a number”); printf(“enter two number”);
scanf(“%d”,&a); scanf(“%d%d”,&a,&b);
If(a%2==0) If(a>b)
{ {
printf(“number is even”); printf(“a is greater”);
} }
getch(); getch();
} }
Example 3 : for print week day name according the given number between 1 to 7.
#include<stdio.h> If(a==4)
#include<conio.h> {
void main() printf(“wednesday”);
{ }
Int a; If(a==5)
clrscr(); {
printf(“enter a number”); printf(“thursday”);
scanf(“%d”,&a); }
If(a==1) If(a==6)
{ {
printf(“sunday”); printf(“friday”);
} }
If(a==2) If(a==7)
{ {
printf(“monday”); printf(“saturday”);
} }
If(a==3) getch();
{ }
printf(“tuesday”);
}
2. if-else statement :
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won‟t. But what if we want to do
something else if the condition is false. Here comes the C else statement. We can use
the else statement with if statement to execute a block of code when the condition is
false.

Syntax :
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example 1 : Example 2 :
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a; int a,b;
clrscr(); clrscr();
printf(“enter a number”); printf(“enter two number”);
scanf(“%d”,&a); scanf(“%d%d”,&a,&b);
if(a%2==0) if(a>b)
{ {
printf(“number is even”); printf(“a is greater”);
} }
else else
{ {
printf(“number is odd”); printf(“b is greater”);
} }
getch(); getch();
} }
3. if-else if-else statement :
Here, a user can decide among multiple options. The C if statements
are executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the C else-if
ladder is bypassed. If none of the conditions are true, then the final else statement will
be executed.
if (condition1)
{
statement;
}
else if (condition2)
{
statement;
}
else if(condition3)
{
Statements;
}
.
.
else
{
statement;
}
Write a program for check a number is positive, negative, or zero.
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf(“enter a number”);
scanf(“%d”,&a);
if(a==0)
{
printf(“number is zero”);
}
else if(a>0)
{
printf(“number is positive”);
}
else if(a<0)
{
printf(“number is negative”);
}
getch();
}
Write a program for check division of a student according to percentage.

#include<stdio.h> }
#include<conio.h> else if(percentage>=36)
void main() {
{ printf(“third division”);
float percentage; }
clrscr(); else
printf(“enter your percentage”); {
scanf(“%f”,&percentage); printf(“fail”);
if(percentage>=60) }
{ getch();
printf(“first division”); }
}
else if(percentage>=45)
{
printf(“second division”);
4. Nested if statement :
A nested if in C is an if statement that is the target of another if statement.
Nested if statements means an if statement inside another if statement. Yes, both C
and C++ allows us to nested if statements with in if statements, i.e, we can place an if
statement inside another if statement.
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
//else statement
}
}
else
{
// else statement
}
Write a program for check greater number between given 3 numbers.

#include<stdio.h> else
#include<conio.h> {
Void main() If(b>c)
{ {
int a,b,c; printf(“b is greater”);
clrscr(); }
printf(“enter three numbers”); else
scanf(“%d%d%d”,&a,&b,&c); {
if(a>b) printf(“c is greater”);
{ }
if(b>c) }
{ getch();
printf(“a is greater”); }
}
else
{
printf(“c is greater”);
}
}
5. Switch case statement :
Switch statement is a control statement that allows us to choose only one
choice among the many given choices. The expression in switch evaluates to return an
Integral or character value, which is then compared to the values present in different
cases. It executes that block of code which matches the case value. If there is no
match, then default block is executed(if present).

Syntax :
.
switch(expression) .
{ .
case 1: case n:
block-1; block-n;
break; break;
case 2: default:
block-2; default-block;
break; break;
case 3: }
block-3;
break;
case 4:
block-4;
break;
Write a program for print week day name according to given number using switch
case.
#include<stdio.h>
#include<conio.h> case 5:
void main() printf(“Thursday”);
{ break;
int n; case 6:
clrscr(); printf(“Friday”);
printf(“enter a number b/w 1 to 7”); break;
scanf(“%d”,&n); case 7:
switch(n) printf(“Saturday”);
{ break;
case 1: default :
printf(“Sunday”); printf(“please choose valid case”);
break; break;
case 2: }
printf(“Monday”); getch();
break; }
case 3:
printf(“Tuesday”);
break;
case 4:
printf(“Wednesday”);
break;
Write a program using switch case statement where we have 4 cases 1 for addition, 2
for subtruction,3 for multipalication and 4 for division.
#include<stdio.h> c= a-b;
#include<conio.h> printf(“%d”,c);
void main() break;
{ case 3:
int n; int a,b,c;
clrscr(); printf(“enter two numbers”);
printf(“enter a number b/w 1 to 4”); scanf(“%d%d”,&a,&b);
scanf(“%d”,&n); c= a*b;
switch(n) printf(“%d”,c);
{ break;
case 1: case 4:
int a,b,c; int a,b,c;
printf(“enter two numbers”); printf(“enter two numbers”);
scanf(“%d%d”,&a,&b); scanf(“%d%d”,&a,&b);
c= a+b; c= a/b;
printf(“%d”,c); printf(“%d”,c);
break; break;
case 2: Default:
int a,b,c; printf(“please choose valid case”);
printf(“enter two numbers”); break;
scanf(“%d%d”,&a,&b); }
getch(); }
Write a program using switch case for print traffic light instruction according to light
signal and also apply case label R, G, Y.
#include<stdio.h>
#include<conio.h> Default:
void main() printf(“please choose valid case”);
{ break;
char ch; }
clrscr(); getch();
printf(“choose a character R,G,Y”); }
scanf(“%c”,&ch);
switch(ch)
{
case „R‟:
case „r‟:
printf(“Stop”);
break;
case „G‟:
case „g‟:
printf(“Go”);
break;
case „Y‟:
case „y‟:
printf(“Ready for go”);
break;
*
- By kanhaiya lal kumawat
A Loop executes the sequence of statements many times until the given condition
becomes false. Suppose we want to print “hello world” 10 times then we have two
Options.
1. We can use 10 printf function to printf 10 time “hello world”.
2. We can use a loop from i=1 to i<=10 and print “hello world” in side block
Example :
Int I;
(1) (2) (4)
For(i=1;i<=10;i++)
{ (3)
printf(“hello world”);
}

Types of loops :
1. for loop
2. while loop
3. do-while loop
1. for loop :
for loop is used to execute a set of statements repeatedly until a particular
condition is satisfied.
Syntax :
(1) (2) (4)
for(initialization; condition; increment/decrement)
{ (3)
statement-block;
}

1. First we need to initialize a variable.


2. We need to check the given condition is true or false, if it‟s true then statement-
block is executed.
3. Then it evaluate the increment/decrement condition and again follows from step 2.
4. If condition is false then control goes to outside loop.
1. Write a program to print “hello world” 10 times.

#include<stdio.h>
#include<conio.h>
Void main()
{
int I;
clrscr();
for (i=1; i<=10 ; i++)
{
printf(“hello world”);
}
getch();
}

Result : hello worldhello worldhello worldhello worldhello worldhello worldhello world


hello worldhello world
Here we can use \t for space and \n for new line.
\t \n
Hello world hello world hello world Hello world
Hello world
Hello world
2. Write a program for print natural numbers.
0123456789

#include<stdio.h>
#include<conio.h>
Void main()
{
int I;
clrscr();
for (i=0; i<10 ; i++)
{
printf(“%d\t”,i);
}
getch();
}

Result :
0123456789
3. Write a program to print all number b/w 50 to 150.
#include<stdio.h>
#include<conio.h>
Void main()
{
int I;
clrscr();
for (i=50; i<=150 ; i++)
{
printf(“%d\t”,i);
}
getch();
}
4. Write a program to print table of a given number.
#include<stdio.h>
#include<conio.h>
Void main()
{ Suppose number is 5.
int I, n,table; Then,
clrscr(); i=1,i<=10(true)
printf(“enter a number”); Then,
scanf(“%d”,&n); table=1*5=5
for (i=1; i<=10 ; i++) i++ = 2
{ table=2*5=10
table=i*n; i++ = 3
printf(“%d\t”,table); table = 3*5=15
}
getch();
}
5. Write a program to print factorial of the given number.

#include<stdio.h>
#include<conio.h>
void main() Factorial of 5= 1*2*3*4*5=120
{
int i, n,fact=1; i=1, fact=1,n=5
clrscr(); Fact=1*1
printf(“enter a number”); Fact =1*2
scanf(“%d”,&n); Fact=2*3
for (i=1; i<=n ; i++) Fact=6*4
{ Fact=24*5
fact=fact*i;
}
printf(“%d”,fact);

getch();
}
6. Write a program to print all even numbers between the given range.

#include<stdio.h>
#include<conio.h>
void main()
{
int min, max,i;
clrscr();
printf(“enter starting and ending number”);
scanf(“%d%d”,&min,&max);
for(i=min;i<=max;i++)
{
if(i%2==0)
{
printf(“%d\t”,i);
}
}
getch();
}
7. Write a program to print all factors of the given number.

#include<stdio.h>
#include<conio.h>
void main()
{
int i, n;
clrscr();
printf(“enter a number”);
scanf(“%d”,&n);
for (i=1; i<=n ; i++)
{
If(n%i==0)
{
printf(“%d”,i);
}
}
getch();
}
8. Write a program for swapping of two integers without using third variable.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“enter two number”);
scanf(“%d%d”,&a,&b);

a=a+b;
b=a-b;
a=a-b;

printf(“after swapping two numbers”);


printf(“a=%d\tb=%d”,a,b);
getch();
}
9. Write a program for swapping of two integers using third variable.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“enter two number”);
scanf(“%d%d”,&a,&b);

c=a;
a=b;
b=c;

printf(“after swapping two numbers”);


printf(“a=%d\tb=%d”,a,b);
getch();
}
2. While loop :
while loop is also known as entry control loop. In this type of loop we have also
three important statements initialization, condition and increment and decrement. Whil
loop also print group of statement repeatedly until the given condition is not satisfied.

Syntax :
initialization; for(initialization ; con ; inc/dec)
while(condition) {
{ statements;
Statements; }
Increment/decrement;
}

#include<stdio.h> }
#include<conio.h> getch();
void main() }
{
int i;
clrscr();
i=1;
while(i<=100)
{
printf(“%d\t”,i);
i++;
Write a program to print table of the given number using while loop.

#include<stdio.h>
#include<conio.h>
void main()
{
int i, n,table;
clrscr();
printf(“enter a number”);
scanf(“%d”,&n);
i=1;
while(i<=10)
{
table=i*n;
printf(“%d”,table);
i++;
}
getch();
}
Write a program to print factorial of the given number using while loop.

#include<stdio.h>
#include<conio.h>
void main()
{
int i, n,fact=1;
clrscr();
printf(“enter a number”);
scanf(“%d”,&n);
i=1;
while(i<=n)
{
fact=fact*I;
i++;
}
Printf(“%d”,fact);
getch();
}
3. do-while loop :
do-while loop is also known as exit control loop. In this type of loop we have
Also three important statements initialization, condition and increment and decrement.
Do-while loop also print group of statement repeatedly until the given condition is not
Satisfied.

Syntax :
Example:
initialization;
do
#include<stdio.h>
{
#include<conio.h>
statements;
void main()
inc/dec;
{
}
int i;
while(condition);
clrscr();
i=1;
do
{
printf(“%d\t”,i);
i++;
}
while(i<=100);
getch();
}
Write a program to print table of the given number using do-while loop.

#include<stdio.h>
#include<conio.h>
void main()
{
int i, n,table;
clrscr();
printf(“enter a number”);
scanf(“%d”,&n);
i=1;
do
{
table=i*n;
printf(“%d”,table);
i++;
}
while(i<=10);
getch();
}
Write a program to print factorial of the given number using do-while loop.

#include<stdio.h>
#include<conio.h>
void main()
{
int i, n,fact=1;
clrscr();
printf(“enter a number”);
scanf(“%d”,&n);
i=1;
do
{
fact=fact*I;
i++;
}
while(i<=n);
Printf(“%d”,fact);
getch();
}
Difference between while and do-while loop :

While do-while
1. While loop is an entry control loop. 1. do-while loop is an exit control loop.
2. In while loop if first time the given 2. But in do-while loop if first time given
condition is false then loop does not condition is false then loop execute
execute. at least once.
3. In this loop we first test the given 3. But in do-while loop we check condition
condition after at take decision. At the end of loop.
Nested for loop :
loop inside another loop is called nested of loop.
Syntax:
for(initialization;condition;inc/dec)
{
for(initialization;condition;inc/dec)
{
statements;
}
}
#include<stdio.h> getch();
#include<conio.h> } * *** *
void main() * *** *
{ * *** *
Int I,j; * *** *
clrscr(); * *** *
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
printf(“*”);
}
printf(“\n”);
}
#include<stdio.h>
#include<conio.h> *
void main() * *
{ * **
Int I,j; * ***
clrscr(); * ****
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“*”);
}
printf(“\n”);
}
getch();
}
#include<stdio.h>
#include<conio.h> 1
void main() 2 2
{ 3 33
Int I,j; 4 444
clrscr(); 5 5555
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d”,i);
}
printf(“\n”);
}
getch();
}
#include<stdio.h>
#include<conio.h> 1
void main() 1 2
{ 1 23
Int I,j; 1 234
clrscr(); 1 2345
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch();
}
#include<stdio.h>
#include<conio.h> 1
void main() 23
{ 456
Int I,j,ch=1; 7 8 9 10
clrscr(); 11 12 13 14 15
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d”,ch);
ch++;
}
printf(“\n”);
}
getch();
}
#include<stdio.h> ASCII-American standard code for information
#include<conio.h> interchange
void main()
{
Int I,j;
Char ch=65;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%c”,ch);
ch++;
}
printf(“\n”);
}
getch();
}
A
BC
DEF
GHIJ
KLMNO
#include<stdio.h>
#include<conio.h> A
void main() BB
{ CCC
Int I,j; DDDD
Char ch=65; EEEEE
clrscr();
for(i=1;i<=5;i++)
{

for(j=1;j<=i;j++)
{
printf(“%c”,ch);
}
ch++;
printf(“\n”);
}
getch();
}
#include<stdio.h>
#include<conio.h> A
void main() BC
{ DEF
Int I,j; GHIJ
Char ch; KLMNO
clrscr();
for(i=1;i<=5;i++)
{
Ch=65;
for(j=1;j<=i;j++)
{
printf(“%c”,ch);
}
printf(“\n”);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j; * * * * *
clrscr(); * *
for(i=0;i<=5;i++) * *
{ * *
for(j=1;j<=5;j++) * *
{ * * * * *
if(i=1 || i=5 || j=1 ||j=5)
{
printf(“*”);
}
else
{
printf(“ “);
}
}
printf(“\n”);
}
getch();
}
Write a program for check a given number is prime or not.
2,3,5,7,11,13,17,19,23………………………n
#include<stdio.h>
#include<conio.h>
void main()
{
Int n,i,temp;
clrscr();
Printf(“enter a number”);
scanf(“%d”,&n);
temp=n;
for(i=2;i<n;i++)
{
If(n%i==0)
{
printf(“number is not prime”);
break;
}
}
If(i==temp)
{
printf(“number is prime”);
}
getch();
}
Write a program for print reverse of the given number.
123 546
321 645

#include<stdio.h>
#include<conio.h>
void main()
{
Int n,r,rev=0;
clrscr();
Printf(“enter a number”);
scanf(“%d”,&n);
while(n>0)
{
r=n%10;
n=n/10;
rev=rev*10+r;
}
printf(“%d”,rev);
getch();
}
Write a program for check a given number is palindrome or not.
1221 141 444
1221 141 444

#include<stdio.h>
#include<conio.h> else
void main() {
{ printf(“not palindrome”);
Int n,r,rev=0,temp; }
clrscr(); getch();
Printf(“enter a number”); }
scanf(“%d”,&n);
temp=n;
while(n>0)
{
r=n%10;
n=n/10;
rev=rev*10+r;
}
if(rev==temp)
{
printf(“palindrome”);
}
*
- By kanhaiya lal kumawat
Control statements are used for control the flow of the loop execution in an program.
In c language we have 4 control statements :

1. Break statement
2. Continue statement
3. Goto statement
4. Exit statement

1. Break statement :
Break statement is used for control the flow of the loop in an program, in an
loop if we apply break statement on the specific condition then the break statement
stop the loop execution.
For example :
if(i==5)
#include<stdio.h>
{
#include<conio.h>
break;
void main()
}
{
printf(“%d”,i);
Int i;
}
clrscr();
getch();
for(i=1;i<=10;i++)
}
{
Result : 1 2 3 4
2. Continue statement :
The continue statement is used inside loops. When a continue statement is
encountered inside a loop, control jumps to the beginning of the loop for next iteration,
skipping the execution of statements inside the body of loop for the current iteration.
For example :

#include<stdio.h>
#include<conio.h>
void main()
{
Int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
{
Continue;
}
printf(“%d”,i);
}
getch();
}

result : 1 2 3 4 6 7 8 9 10
3. Goto statement :
The goto statement is a jump statement which is sometimes also referred to
as unconditional jump statement. The goto statement can be used to jump from
anywhere to anywhere within a function.

For example :
#include <stdio.h>
#include<conio.h>
void main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d”,num*i);
i++;
if(i<=10)
{
goto table;
}
}
4. Exit statement :
break statement stop the loop execution but the exit statement also stop
Program execution on a specific condition. <stdlib.h> header file is used for exit
Statement.

For example :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
Int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
{
exit(1);
}
printf(“%d”,i);
}
getch();
}
*
- By kanhaiya lal kumawat
An array is a collection of similar types of data means an integer type array storage
Integer type values, and an float type array store float type values.

Array concept is used for store similar type values in a single variable and these value
Have also continues memory location.

Declaration of an array :
int number[10]={1,2,3,56,78,88,56,45,76,34};
float number[10]={1.2,2.3,3.4,4.5,5.6,6.7,7.8,8.9,9.0,2.1};

name of array number


1 2 3 4 5 6 7 8 9 10
Total size=20
100 102 104 106 108 110 112 114 116 118
Types of array :
1. One dimensional array
2. Multi dimensional array

1. One dimensional array :

Declaration of one dimensional array :


data_type array_name[array_size];
Example :
int marks[5];
Initialization of one dimensional array :

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Program for print array elements

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int i; int i;
int marks[5];//declaration of array int marks[5]={80,60,70,85,75};
marks[0]=80;//initialization of array for(i=0;i<5;i++)
marks[1]=60; {
marks[2]=70; printf("%d \n",marks[i]);
marks[3]=85; }
marks[4]=75; getch();
//traversal of array }
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
getch();
} Output :
80 60 70 85 75
Program for print array elements where elements are entered by user

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
int marks[5];//declaration of array
printf(“enter array elements”);
for(i=0;i<5;i++)
{
scanf("%d \n",&marks[i]);
}
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
getch();
}
Program for print array elements in reverse order where elements are entered by
user
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
int marks[5];//declaration of array
printf(“enter array elements”);
for(i=0;i<5;i++)
{
scanf("%d \n",&marks[i]);
}
//traversal of array
for(i=4;i>=0;i--)
{
printf("%d \n",marks[i]);
}
getch();
}
Write a program for print sum of given array elements

#include<stdio.h>
#include<conio.h>
void main() 10 20 30 40 50
{
int i; Sum=0+10=10
int marks[5],sum=0; Sum=10+20=30
printf(“enter array elements”); Sum=30+30=60
for(i=0;i<5;i++) Sum=60+40=100
{ Sum=100+50=150
scanf("%d \n",&marks[i]);
}
for(i=0;i<5;i++)
{
sum=sum+marks[i];
}
printf("%d \n",sum);
getch();
}
Write a program for print average of given array elements

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
int marks[5],sum=0;
Float average;
printf(“enter array elements”);
for(i=0;i<5;i++)
{
scanf("%d \n",&marks[i]);
}
for(i=0;i<5;i++)
{
sum=sum+marks[i];
}
average=(float)sum/i;
printf(“%f”,average);
getch();
}
Write a program for print smallest element from an array.

#include<stdio.h>
7 9 5 90 45
#include<conio.h>
void main()
{
int i;
int marks[5];
int smallest;

for(i=0;i<5;i++)
{
printf(“enter array elements”);
scanf("%d \n",&marks[i]);
}
smallest=marks[0];
for(i=1;i<5;i++)
{
If(smallest>marks[i])
{
smallest=marks[i];
}}
printf(“%d”,smallest);
getch();
Write a program for print largest number form an given integer array.
#include<stdio.h>
#include<conio.h>
void main()
{ 7 9 5 90 45
int i;
int marks[5];
int largest;
clrscr();
printf("enter array elements");
for(i=0;i<5;i++)
{
scanf("%d\n",&marks[i]);
}
largest=marks[0];
for(i=1;i<5;i++)
{
if(largest<marks[i])
{
largest=marks[i];
}
}
printf("%d",largest);
getch();
2. Multi-dimensional arrray :
Multi dimensional array may be two dimensional or three
Dimensional means 2D and 3D.
1. Two dimensional
2. Three dimensional
1. Two dimensional array :
two dimensional array means array of array. It is also known as
matrix or tabular array

Declaration of 2D array :
Data_type array_name[row][column]
Example :
int A[3][3]={1,2,3,4,5,6,7,8,9};

0 1 2

0 A[0][0] A[0][1] A[0][2]


1 A[1][0] A[1][1] A[1][2]
2 A[2][0] A[2][1] A[2][2]

1 2 3
4 5 6
7 8 9
Write a program for print elements of two dimensional array.
#include<stdio.h>
#include<conio.h>
void main()
{
Int I,j;
Int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
clrscr();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}

Result :
1 2 3
4 5 6
7 8 9
Write a program for print elements of two dimensional array where elments entered
by user.
#include<stdio.h> printf(“\n”);
#include<conio.h> }
void main()
{ Result :
Int I,j; 1 2 3
Int a[3][3]; 4 5 6
clrscr(); 7 8 9
printf(“enter array elements”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d\t”,&a[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,a[i][j]);
}
Write a program for print addition of two two dimensional array elements.
#include<stdio.h>
#include<conio.h> printf(“addition of two matrix”);
void main() for(i=0;i<3;i++)
{ {
Int I,j; for(j=0;j<3;j++)
Int a[3][3],b[3][3],c[3][3]; {
clrscr(); c[i][j]=a[i][j]+b[i][j];
printf(“enter first array elements”); printf(“%d\t”,c[i][j]);
for(i=0;i<3;i++) }
{ printf(“\n”);
for(j=0;j<3;j++) }
{ getch();
scanf(“%d\t”,&a[i][j]); }
} Result :
}
3 4 5 4 6 8
printf(“enter second array elements”);
6 7 8
for(i=0;i<3;i++) + 10 12 14
{ 1 2 3 16 18 20
for(j=0;j<3;j++)
{ 7 10 13
scanf(“%d\t”,&b[i][j]); 16 19 22
}
} 17 20 23
Write a program for print two matrix multiplication.

#include<stdio.h> {
#include<conio.h> scanf(“%d”,&a[i][j]);
Void main() }
{ }
Int a[2][2],b[2][2],c[2][2]; Printf(“enter second matrix elements :”);
Int i,j,k; for(i=0;i<2;i++)
clrscr(); {
Printf(“enter first matrix elements :”); for(j=0;j<2;j++)
for(i=0;i<2;i++) {
{ scanf(“%d”,&b[i][j]);
for(j=0;j<2;j++) }}
printf("multiply of the matrix :\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++) 1 2 5 6
{
c[i][j]=0; 3 4 0 7
for(k=0;k<2;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j]; i=0,j=0,k=0
} C[0][0]=0;
} C[0][0]=c[0][0]+a[0][0]*b[0][0];
} C[0][0]=0+1*5=5;
//for printing result C[0][0]=5+2*0=5;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
Write a program for print transpose of a matric.

#include<stdio.h>
#include<conio.h>
Void main()
{
Int a[3][3],ta[3][3];
Int i,j;
clrscr();
Printf(“enter matrix elements :”);
for(i=0;i<3;i++)
{ printf("Transpose of given matrix: \n");
for(j=0;j<3;j++) for(i=0;i<3;i++)
{ {
scanf(“%d”,&a[i][j]); for(j=0;j<3;j++)
} {
} printf("%d\t ", ta[i][j]);
for(i=0; i<3;i++) }
{ printf("\n");
for(j=0;j<3;j++) }
{ getch();
ta[i][j] = a[j][i]; }
}
}
Write a program for print diagonal matrix.

#include<stdio.h>
for(i=0;i<3;i++)
#include<conio.h>
{
void main()
for(j=0;j<3;j++)
{
{
int i,j;
printf("%d\t",a[i][j]);
int a[3][3];
}
clrscr();
printf("\n");
for(i=0;i<3;i++)
}
{
getch();
for(j=0;j<3;j++)
}
{
if(i==j)
1 0 0
{
0 1 0
a[i][j]=1;
0 0 1
}
else
{
a[i][j]=0;
}
}
}
*
- By kanhaiya lal kumawat
String is a character type array, so we can store many characters in the character
array. And an string is a collection of characters. In c programming string is always
written in double quotation mark.
For example :
“kanhaiya”

Syntax :
char array_name[size];

Declaration and initilization :


char name[10]={„k‟,‟a‟,‟n‟,‟h‟,‟a‟,‟I‟,‟y‟,‟a‟};
char name[10]=“kanhaiya”;

Note : in array at the last always have null character „\0‟.


String programs :
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
Void main() Void main()
{ {
char name[10]=“kanhaiya”; char name[10];
clrscr(); clrscr();
printf(“%s”,name); printf(“enter your name”);
getch(); scanf(“%s”,&name);
} printf(“%s”,name);
getch();
#include<stdio.h> }
#include<conio.h>
Void main() #include<stdio.h>
{ #include<conio.h>
Int i; Void main()
char name[10]={„k‟,‟a‟,‟n‟,‟h‟,‟a‟,‟I‟,‟y‟,‟a‟}; {
clrscr(); char name[10];
for(i=0;i<=8;i++) clrscr();
{ puts(“enter your name”);
printf(“%c”,name[i]); gets(name);
} puts(name);
getch(); getch();
} }
String function :
string functions are use full for manipulate the string. These
functions stored in string.h header file. So it‟s compulsory to add this header file.

1. strlen() function :
this function is used for calculate the length of the string characters.
Example :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20];
Int i;
clrscr();
puts(“enter your name”);
gets(name);
i = strlen(name);
printf(“%d”,i);
getch();
}
2. strrev() function :
strrev() function is used for print string in reverse order.
Example :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20];
clrscr();
puts(“enter your name”);
gets(name);
puts(strrev(name));
getch();
}
3. strcmp() function :
compare two strings. If string one is greater then result is positive and
If string two is greater then result is negative number and both strings are equal then
Result is zero.

Example :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20],nick_name[20];
Int i;
clrscr();
puts(“enter your name”);
gets(name);
Puts(“enter your nick name”);
gets(nick_name);
i=strcmp(name,nick_name);
printf(“%d”,i);
getch();
}
4. strcpy() function :
strcpy function is used for copy a string to another.

Example :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20],nick_name[20];
Int i;
clrscr();
puts(“enter your name”);
gets(name);
Puts(“enter your nick name”);
gets(nick_name);
strcpy(name,nick_name);
puts(“name”);
getch();
}
Note : when string two coping into the string one then value of string one is removed
And string 2’s value is copyed there.
5. strcat() function :
concatenate two strings.

Example :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char first_name[20],last_name[20];
Int i;
clrscr();
puts(“enter your first name”);
gets(first_name);
Puts(“enter your last name”);
gets(last_name);
strcat(first_name,last_name);
puts(“first_name”);
getch();
}
*
- By kanhaiya lal kumawat
A function is a block of code that performs a particular task. There are many situations
where we might need to write same line of code for more than once in a program. This
may lead to unnecessary repetition of code, bugs and even becomes boring for the
programmer. So, C language provides an approach in which you can declare and define
a group of statements once in the form of a function and it can be called and used
whenever required.
These functions defined by the user are also know as User-defined Functions.

C functions can be classified into two categories,


1. Library functions
2. User-defined functions

1. Library functions are those functions which are already defined in C library, example
printf(), scanf(), strcat() etc. You just need to include appropriate header files to use
these functions. These are already declared and defined in C libraries.

2. A User-defined functions on the other hand, are those functions which are defined
by the user at the time of writing program. These functions are made for code reusabilit
and for saving time and space.
Benefits of Using Functions
• It provides modularity to your program's structure.
• It makes your code reusable. You just have to call the function by its name to use it,
wherever required.
• In case of large programs with thousands of code lines, debugging and editing become
easier if you use functions.
• It makes the program more readable and easy to understand.

Important steps for create a function :


1. Declaration
2. Defination
3. calling

1. Function Declaration :
returntype functionName(type1 parameter1, type2 parameter2,...);

Like any variable or an array, a function must also be declared before its used. Function
declaration informs the compiler about the function name, parameters is accept, and its
return type. The actual body of the function can be defined separately. It's also called as
Function Prototyping. Function declaration consists of 4 parts.
• returntype
• function name
• parameter list
• terminating semicolon
Returntype :
When a function is declared to perform some sort of calculation or any operation and is
expected to provide with some result at the end, in such cases, a return statement is
added at the end of function body. Return type specifies the type of value(int, float,
char, double) that function is expected to return to the program which called the
function.
Note: In case your function doesn't return any value, the return type would be void.

functionName :
Function name is an identifier and it specifies the name of the function. The function
name is any valid C identifier and therefore must follow the same naming rules like
other variables in C language.

parameter list :
The parameter list declares the type and number of arguments that the function
expects when it is called. Also, the parameters in the parameter list receives the
argument values when the function is called. They are often referred as formal
parameters.
2. Definition :

return_type function_name(parameter_list)
{
code of function;
}

3. Calling :

function_name(parameter_list);
Example of function :
#include<stdio.h>
#include<conio.h>

void myfunction(); //declaration

void myfunction() // definition


{
printf(“this is my first function program”);
}

void main()
{
clrscr();
myfunction(); // calling
getch();
}
Write a program for addition of two numbers using function.
#include<stdio.h>
#include<conio.h>

void add(); //declaration

void add() // definition


{
int a,b;
printf(“enter two numbers”);
scanf(“%d%d”,&a,&b);
printf(“%d”,a+b);
}

void main()
{
clrscr();
add(); // calling
add();
getch();
}
Write a program for check a number is even or odd using function.
#include<stdio.h>
#include<conio.h>
void main()
{
void evenodd(); //declaration
clrscr();
evenodd(); // calling
void evenodd() // definition
evenodd();
{
getch();
int a;
}
printf(“enter a number”);
scanf(“%d”,&a);
if(a%2==0)
{
printf(“number is even”);
}
else
{
printf(“number is even”);
}
}
Nesting of function :
nesting of function is not possible in function. But we can only declare a
function in another function.
#include<stdio.h>
void main()
#include<conio.h>
{
void kanhaiya();
clrscr();
void kanhaiya()
kanhaiya();
{
sikar();
printf(“my name is kanhaiya”);
rajasthan();
void sikar();
getch();
}
}
void sikar()
{
printf(“I am from sikar”);
void rajasthan();
}
void rajasthan()
{
printf(“state rajasthan”);
}
Types of user define functions :
four types.
1. No arguments and No return type
2. No arguments and A return type
3. A argument and No return type
4. A argument and A return type

Declaration :

return _type function_name(argument_list);

1. No arguments and No return type :


void add();
2. No arguments and A return type :
int add();
3. A argument and No return type :
void add(int x,int y);
4. A argument and A return type:
int add(int x, int y);

Here return type may be int, float, char, double or void.


Defination :

return _type function_name(argument_list)


{
// block of code
}

1. No arguments and No return type :


void add()
{
int a=8,b=10;
printf(“%d”,a+b);
}
2. No arguments and A return type :
int add()
{
int a=8,b=10;
printf(“%d”,a+b);
return 0;
}
3. A argument and No return type :
void add(int a, int b)
{
printf(“%d”,a+b);
}
4. A argument and A return type:
int add(int a, int b)
{
printf(“%d”,a+b);
return 0;
}
Write a program for addition of two numbers using function.
NO argument and NO return type
#include<stdio.h>
#include<conio.h>

void add(); //declaration

void add() // definition


{
int a,b;
printf(“enter two numbers”);
scanf(“%d%d”,&a,&b);
printf(“%d”,a+b);
}

void main()
{
clrscr();
add(); // calling
add();
getch();
}
Write a program for addition of two numbers using function.
NO argument and A return type
#include<stdio.h>
#include<conio.h>

int add(); //declaration

int add() // definition


{
int a,b;
printf(“enter two numbers”);
scanf(“%d%d”,&a,&b);
printf(“%d”,a+b);
return 0;
}

void main()
{
clrscr();
add(); // calling
add();
getch();
}
Write a program for addition of two numbers using function.
A argument and NO return type
#include<stdio.h>
#include<conio.h>

void add(int a, int b); //declaration

void add(int a, int b) // definition


{
printf(“%d”,a+b);
}

void main()
{
Int a=8,b=10;
clrscr();
add(a,b); // calling
add(a,b);
getch();
}
Write a program for addition of two numbers using function.
A argument and A return type
#include<stdio.h>
#include<conio.h>

float add(int a, int b); //declaration

float add(int a, int b) // definition


{
printf(“%d”,a+b);
return 10.00;
}

void main()
{
Int a=8.9,b=10.5;
clrscr();
add(a,b); // calling
add(a,b);
getch();
}
Write a program for print table of the given number using function.

NO argument and NO return type


#include<stdio.h>
#include<conio.h>
void table(); //declaration
void table() // definition
{
int n,i,table;
printf(“enter a number”);
scanf(“%d”,&n);
for(i=1;i<=10;i++)
{
table=i*n;
printf(“%d\n”,table);
}
}
void main()
{
clrscr();
table(); // calling
getch();
}
Write a program for print table of the given number using function.

NO argument and A return type


#include<stdio.h>
#include<conio.h>
int table(); //declaration
int table() // definition
{
int n,i,table;
printf(“enter a number”);
scanf(“%d”,&n);
for(i=1;i<=10;i++)
{
table=i*n;
printf(“%d\n”,table);
}
Return 0;
}
void main()
{
clrscr();
table(); // calling
getch();
}
Write a program for print table of the given number using function.

A argument and NO return type


#include<stdio.h>
#include<conio.h>
void table(int n); //declaration
void table(int n) // definition
{
int i,table;
for(i=1;i<=10;i++)
{
table=i*n;
printf(“%d\n”,table);
}
}
void main()
{
Int n;
printf(“enter a number”);
scanf(“%d”,&n);
clrscr();
table(n); // calling
getch();
}
Write a program for print table of the given number using function.

A argument and A return type


#include<stdio.h>
#include<conio.h>
int table(int n); //declaration
int table(int n) // definition
{
int i,table;
for(i=1;i<=10;i++)
{
table=i*n;
printf(“%d\n”,table);
}
return 0;
}
void main()
{
Int n;
printf(“enter a number”);
scanf(“%d”,&n);
clrscr();
table(n); // calling
getch();
}
*
-by kanhaiya lal kumawat
Definition :
structure is an user-defined data type. In which we can store many type of
values like integer, float, char, string etc. structure is like an array but array can hold
Single type of values but structure can hold all type of values in single structure.

Syntax :
struct sturcture_name
{
datatype1 item1;
datatype1 item1;
datatype1 item1;
datatype1 item1;
}
Example :
struct book
{
char book_name[20];
int book_pages;
float book_price;
}
Initialization of an structure :

struct book bk ={“c_language”,200,230.89};


Simple structure program :
#include<stdio.h>
#include<conio.h> struct book bk;
Void mian() bk.book_name=“c_language”;
{ bk.pages=200;
struct book bk.price=230.89;
{
char book_name[20];
int pages;
float price;
};

struct book bk = {“c_language”,200,230.89};


printf(“%s”,bk.book_name);
printf(“%d”,bk.pages);
printf(“%f”,bk.price);
getch();
}

Note : here we can also declare structure outside the void main function and
Initialize by different ways.
Values of structure input by user :
#include<stdio.h>
#include<conio.h>
Void main()
{
struct book
{
char book_name[20];
int pages;
float price;
};

struct book bk;


printf(“enter book_name, pages, price);
scanf(“%s”,&bk.book_name);
scanf(“%d”,&bk.pages);
scanf(“%f”,&bk.price);

printf(“%s”,bk.book_name);
printf(“%d”,bk.pages);
printf(“%f”,bk.price);
getch();
}
Write a program for print an student details using structure where details are rollnumber
, name, course, gender and fathers name.
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int rollnumber;
char name[20];
char course[20];
char gender[10];
char f_name[20];
};
struct student s1;
printf(“enter student rollnumber, name, course, gender, father‟s name”);
scanf(“%d%s%s%s%s”,&s1.rollnumber,&s1.name,&s1.course,&s1.gerder,&s1.f_name”);
printf(“%d%s%s%s%s”,s1.rollnumber,s1.name,s1.course,s1.gerder,s1.f_name”);
getch();
}
Array of structure :
we can create array type variable of any structure. And use it many
times using loop.
Example :
#include<stdio.h> for(i=0;i<5;i++)
#include<conio.h> {
void main() printf(“%d%s%s%s%s”,s1[i].rollnumber,s1[i].name,
{ s1[i].course,s1[i].gerder,s1[i].f_name”);
struct student }
{ getch();
int rollnumber; }
char name[20];
char course[20];
char gender[20];
char f_name[20];
};
struct student s1[5];
for(i=0;i<5;i++)
{
printf(“enter student rollnumber, name, course, gender, father‟s name”);
scanf(“%d%s%s%s%s”,&s1[i].rollnumber,&s1[i].name,&s1[i].course,&s1[i].gerder,
&s1[i].f_name”);
}
Structure of structure :
It means we can create object of an structure in another structure.
Syntax :
struct structure1
{ struct address
datatype1 member1; {
datatype1 member1; char city[20];
datatype1 member1; char state[20];
datatype1 member1; long int pincode;
}; };

struct structure2 struct student


{ {
datatype1 member1; int rollnumber;
datatype1 member1; char name[20];
datatype1 member1; char gender[20];
struct structure1 s1; struct address a1;
}; }
Program :
#include<stdio.h>
#include<conio.h> printf(“%d%s%s%s%s%d”,s1.rollnumber,s1.name,s1.gerder,
void main() s1.a1.city,s1.a1.state,s1.a1.pincode”);
{ getch();
struct address }
{
char city[20];
char state[20];
long int pincode;
};
struct student
{
int rollnumber;
char name[20];
char gender[10];
struct address a1;
};
struct student s1;
printf(“enter student rollnumber, name, gender, city, state, pincode”);
scanf(“%d%s%s%s%s%d”,&s1.rollnumber,&s1.name,&s1.gerder,&s1.a1.city,&s1.a1.state,
&s1.a1.pincode”);
*
- By kanhaiya lal kumawat
Union :
union is an user define data-type and it is also like an structure but an structure‟s size is
depend on all members of the structure but in union the size of union is maximum
Variable‟s size.
And in union all data members of the union share common memory location so in union
We can store only single value at a time.

Structure Union
struct book union book
{ {
char name[20]; char name[20];
int pages; int pages;
float price; float price;
}; };

name name

pages price pages price

Total size : 26 Total size : 20


Program :
#include<stdio.h>
#include<conio.h>
Void main()
{
union book
{
char name[20];
float price;
int pages;
};
union book bk1;
bk1.name=“c_language”;
printf(“%s”,bk1.name);
getch();
}
*
- By kanhaiya lal kumawat
Local Variable
A variable that is declared inside the function or block is called a local variable
It must be declared at the start of the block. You must have to initialize the local
variable before it is used.

Example :
#include<stdio.h>
#include<conio.h>
void main()
{
int x=10;//local variable
printf(“%d”,x);
getch();
}
Global Variable
A variable that is declared outside the function or block is called a 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 program.

Example :
#include<stdio.h>
#include<conio.h>
int value=20;//global variable
void function1()
{
int x=10;//local variable
printf(“%d”,x);
printf(“%d”,value);
getch();
}
*
- By kanhaiya lal kumawat
Storage classes in C are used to determine the lifetime, visibility, memory location, and
initial value of a variable.
• scope i.e where the value of the variable would be available inside a program.
• default initial value i.e if we do not explicitly initialize that variable, what will be
its default initial value.
• lifetime of that variable i.e for how long will that variable exist.

There are four types of storage classes in C


1. Automatic
2. External
3. Static
4. Register

Storage Classes Storage Place Default Value Scope Lifetime


auto RAM Garbage Value Local Within function
extern RAM Zero Global Till the end of the main
program Maybe
declared anywhere in
the program
static RAM Zero Local,global Till the end of the main
program, Retains value
between multiple
functions call
register Register Garbage Value Local Within the function
1. Automatic storage class :
Automatic variables are allocate memory automatically at runtime. We can use
automatic variable class inside a particular block where this variable is used.

Example :
#include<stdio.h>
#include<conio.h>
void main()
{
auto int a;
printf(“%d”,a);
getch();
}
• The automatic variables are initialized to garbage by default.
• Keyword that used for defining automatic variables is auto.
• Every local variable is automatic in c by default.
• It‟s scope is local variable.
• This variable store in computer memory(RAM).
2. Register storage class :
The register variable is stored in the computer CPU register. And the register
Access is faster then the memory access. If the CPU register memory is full then the
value of register variable is store on the memory.
When you declare float and double type variable as register, it treats as auto variable
because it takes more space to store.

Example :
#include<stdio.>
#include<conio.h>
void main()
{
register int num;
for(num=1;num<=5;num++)
{
printf(“%d”,num);
}
getch();
}
3. External storage class :
when you are declaring the variables as external storage class, it is accessed in
all the functions which is defined in the same program. These variables are called
extern or global variables. External variables are declared outside the function body.
In case both external and auto variables are declared with the same name in a program,
The first priority is given to the auto variable.

Example :
#include<stdio.h>
#include<conio.h>
extern int num=5;
void display();
void display()
{
printf(“%d”,num);
}
void main()
{
Int num=20;
printf(“%d”,num);
display();
getch();
}
4. Static storage class :
The static variable may be of an auto and global type depending upon where
It is declared. If declared outside the function of the body it will be static global. In
Case, if it is declared in the particular block, it is treated as the local or auto variable.
a static variable is initialized only once, it is never reinitialized. The value of
the static variable save at each call.
Example :
#include<stdio.h>
#include<conio.h>
void count();
void count()
{
Static int num=1;
printf(“%d”,num);
num++;
}
void main()
{
count();
count();
count();
getch();
}
*
- By kanhaiya lal kumawat
The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function, or any other pointer. The size of
the pointer variable is always 2 bytes.

Example :
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of
type integer.

Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char

Pointer Example
An example of using pointers to print the address and value is given below.

B A

2000 10

3000 2000
Example 1: Example 2:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int number=50; int a=5,b=10;
int *p; int *A=&a, *B=&b;
p=&number; Int c;
printf(“%d”,number); c=*A+*B;
printf(“%d”,&number); printf(“%d”,c);
printf("Address of p variable is %x \n",p); getch();
printf("Value of p variable is %d \n",*p); }
getch();
}
Example 3 :
#include<stdio.h>
#include<conio.h>
void main()
{
int a=8,b=10;
int *A=&a, *B=&b;
*A=*A+*B;
*B=*A-*B;
*A=*A-*B;
printf(“%d\n%d”,*A,*B);
getch();
}
Array of Pointer :
we can store address of an array onto the pointer type array.

Declaration of array of pointer :


int *p[7];
Example :

#include<stdio.h>
#include<conio.h>
void main()
{
int marks[5]={50,60,70,80,90};
int i, *p[5];

for(i=0;i<5;i++)
{
p[i]=&marks[i];
}
for(i=0;i<5;i++)
{
printf(“%d”,*p[i]);
}
getch();
}
Write a program for print sum of array elements using pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
int marks[5]={40,50,60,70,80};
int i,*p[5],sum=0;
for(i=0;i<5;i++)
{
p[i]=&marks[i];
}
for(i=0;i<5;i++)
{
sum=sum+*p[i];
}
printf(“%d”,sum);
getch();
}
Pointer to pointer :
Pointer is known as a variable that contain address of another variable. The
pointer variable also has an address. The pointer variable containing address of another
pointer is known as pointer of pointer.

Pointer of pointer pointer variable


address address value

**c *b a
-14 -12 9
-16 -14 -12

Pointer of pointer is declared by double asterisk symbol.


Value of x=5;
Address of x=2000;
Value of p=2000
Value of *p=5
Address of *p=3000;
Value of P=3000;
Value of **P=5;
Address of **p=4000
Example of pointer to pointer :

#include<stdio.h>
#include<conio.h>
void main()
{
int var=3000;
int *p=&var;
int **P=&p;

printf(“%d”,var);
printf(“%d”,&var);
printf(“%d”,p);
printf(“%d”,*p);
printf(“%d”,&*p);
printf(“%d”,&p);
printf(“%d”,P);
printf(“%d”,**P);
printf(“%d”,&**P);
printf(“%d”,&P);
getch();
}
Pointer as function argument :
pointer as a function argument is used to hold addresses of arguments
passed during function call. This is known as call by reference. When a function is
called by reference any change made to the reference variable with effect the
original variable.
Write a program for swapping two numbers using pointer as function argument.
#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b);
void swap(int *a,int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
printf(“%d\n%d”,a,b);
}
void main()
{
int m=10,n=20;
swap(&m,&n);
printf(“%d\n%d”,m,n);
getch();
}
Pointer to structure :
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
char name[10];
int rollnumber;
};
struct student s1={“kanhaiya”,12};
struct student *st;
st =&s1;
printf(“%s\n”,s1.name);
printf(“%d\n”,s1.rollnumber);
printf(“%s\n”,*st->name);
printf(“%d\n”,*st->rollnumber);
getch();
}
Arrow symbol is used when we want to access structure members by
pointer variable.
File Handling in C :
In programming, we may require some specific input data to be generated several
numbers of times. Sometimes, it is not enough to only display the data on the console.
The data to be displayed may be very large, and only a limited amount of data can be
displayed on the console, and since the memory is volatile, it is impossible to recover
the programmatically generated data again and again. However, if we need to do so,
we may store it onto the local file system which is volatile and can be accessed every
time. Here, comes the need of file handling in C.

File handling in C enables us to create, update, read, and delete the files stored on the
local file system through our C program. The following operations can be performed on
a file.

1. Creation of the new file


2. Opening an existing file
3. Reading from the file
4. Writing to the file
5. Deleting the file
Functions for file handling
There are many functions in the C library to open, read, write, search and close the file
A list of file functions are given below:
No. Function Description
1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file


7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file


1. fopen() :
We must open a file before it can be read, write, or update. The fopen() function is
used to open a file. The syntax of the fopen() is given below.

Syntax :
FILE *fopen( const char * filename, const char * mode );

The fopen() function accepts two parameters:


The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be like
"c://some_folder/some_file.ext".
The mode in which the file is to be opened. It is a string.

Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
The fopen function works in the following way.
• Firstly, It searches the file to be opened.
• Then, it loads the file from the disk and place it into the buffer. The buffer is used to
provide efficiency for the read operations.
• It sets up a character pointer which points to the first character of the file.

#include<stdio.h>
#include<conio.h>
void main( )
{
FILE *fp;
char ch=„a‟;
fp = fopen("file_handle.txt",“w") ;
printf("%c",ch);
fprintf(fp,”%c”,ch);
fclose (fp );
getch();
}
2. fprintf() :
The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream.
Syntax:
fprintf(FILE *stream, const char *format [, argument, ...])

Example :
#include <stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
getch();
}
3. fscanf() :
The fscanf() function is used to read set of characters from file.

Example :
#include<stdio.h> Example 2:
#include<conio.h> #include<stdio.h>
void main() #include<conio.h>
{ void main()
FILE *fp; {
char ch[10]="kanhaiya"; char ch[10];
clrscr(); FILE *fp;
fp=fopen("alpha.txt","w"); fp=fopen("alpha.txt","r");
fprintf(fp,"%s",ch); fscanf(fp,"%s",ch);
printf("%s",ch); printf("%s",ch);
fclose(fp); fclose(fp);
getch(); getch();
} }

First example for create a text file for store a string. And second example for show
Output of the first example on the console screen.
4. fclose() :
The fclose() function is used to close a file. The file must be closed after performing all
the operations on it. The syntax of fclose() function is given below:
Syntax :
fclose( FILE *fp );

5. fputc() function :
The fputc() function is used to write a single character into file. It outputs a character
to a stream.
Syntax:
fputc(int c, FILE *stream)
Example :
#include <stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp = fopen("file1.txt", "w");
fputc('a',fp);
fclose(fp);
getch();
}
6. fgetc() function :
The fgetc() function returns a single character from the file. It gets a character from
the stream. It returns EOF at the end of file.
Syntax:
fgetc(FILE *stream)

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("myfile.txt","r");
c=fgetc(fp);
printf("%c",c);
fclose(fp);
getch();
}
7. fputs() function :
The fputs() function writes a line of characters into file. It outputs string to a stream.
Syntax:
fputs(const char *s, FILE *stream)

Example :
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
clrscr();

fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);

fclose(fp);
getch();
}
8. fgets() :
The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax:
fgets(char *s, int n, FILE *stream)

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char text[300];
clrscr();

fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));

fclose(fp);
getch();
}
9. fseek() function :
The fseek() function is used to set the file pointer to the specified offset. It is used to
write data into file at desired location.
Syntax:
fseek(FILE *stream, long int offset, int whence)

There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR
and SEEK_END.

Example :
#include <stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is javatpoint", fp);
fseek( fp, 7, SEEK_SET );
fputs("sonoo jaiswal", fp);
fclose(fp);
getch();
}
10. C rewind() function :
The rewind() function sets the file pointer at the beginning of the stream. It is useful if
you have to use stream many times.

Syntax:
while((c=fgetc(fp))!=EOF)
rewind(FILE *stream)
{
printf("%c",c);
Example :
}
#include<stdio.h>
fclose(fp);
#include<conio.h>
getch();
void main()
}
{
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
rewind(fp);//moves the file pointer at beginning of the file

As you can see, rewind() function moves the file pointer at beginning of the file that
why "this is simple text" is printed 2 times. If you don't call rewind() function, "this is
simple text" will be printed only once.
12. C ftell() function :
The ftell() function returns the current file position of the specified stream. We can use
ftell() function to get the total size of a file after moving file pointer at the end of file.
We can use SEEK_END constant to move the file pointer at the end of file.

Syntax:
int ftell(FILE *stream)
Example :
#include <stdio.h>
#include <conio.h>
void main (){
FILE *fp;
int length;
clrscr();
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);

length = ftell(fp);

fclose(fp);
printf("Size of file: %d bytes", length);
getch();
}
Memory allocation:
Memory allocation is the process of setting sections of memory in a program to be used
to store variables.
There are two types of memory allocation:
1. Static memory allocation
2. Dynamic memory allocation

1. Static memory allocation:


In static memory allocation when we declare a variable in a program the memory
Allocate at compile time are called static memory allocation.
Example:
int x;
Char ch;

2. Dynamic memory allocation;


The process of allocating memory at runtime is known as dynamic memory allocation.
Memory management functions are used for allocating and freeing memory during
Execution of a program. These functions are define in stdlib.h header file.
Difference between static and dynamic memory allocation :

static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while executing memory can be increased while executing
program. program.
used in array. used in linked list.
Functions of dynamic memory allocation:
1. malloc()
2. calloc()
3. realloc()
4. free()

1. malloc() function :
• The malloc() function allocates single block of requested memory.
• It doesn't initialize memory at execution time, so it has garbage value initially.
• It returns NULL if memory is not sufficient.

syntax:
ptr=(cast-type*)malloc(byte-size)

Example :
int *x;
x=(int*)malloc(50*sizeof(int));
//memory space allocated to variablex.
free();
// release the memory allocated to variable x.
2. calloc() function :
• The calloc() function allocates multiple block of requested memory.
• It initially initialize all bytes to zero.
• It returns NULL if memory is not sufficient.
• Calloc function is normally used for derived datatypes like array ,structure etc.

Syntax:
ptr=(cast-type*)calloc(number, byte-size)

Example:
Struct employee
{
Char *name;
Int salary;
};

typedef struct employee emp;


emp *e1;
e1=(emp*)calloc(30,sizeof(emp));
3. realloc() function :
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by
realloc() function. In short, it changes the memory size.

Syntax :
ptr=realloc(ptr, new-size)

Example:
Int *x;
X=(int*)malloc(50*sizeof(int));
X=(int*)realloc(x,200);

4. free() function :
The memory occupied by malloc() or calloc() functions must be released by calling
free() function. Otherwise, it will consume memory until program exit.

Example :
free(ptr)
Linked list in c language :
Linked List can be defined as collection of objects called nodes that are randomly
stored in the memory. A node contains two fields i.e. data stored at that particular
address and the pointer which contains the address of the next node in the memory.
The last node of the list contains pointer to the null.

Uses of Linked List :


• The list is not required to be contiguously present in the memory. The node can reside
any where in the memory and linked together to make a list. This achieves optimized
utilization of space.
• list size is limited to the memory size and doesn't need to be declared in advance.
Empty node can not be present in the linked list.
• We can store values of primitive types or objects in the singly linked list.
Why use linked list over array?
Till now, we were using array data structure to organize the group of elements that are
to be stored individually in the memory. However, Array has several advantages and
disadvantages which must be known in order to decide the data structure which will be
used throughout the program.

Array contains following limitations:


• The size of array must be known in advance before using it in the program.
• Increasing size of the array is a time taking process. It is almost impossible to expand
the size of the array at run time.
• All the elements in the array need to be contiguously stored in the memory. Inserting
any element in the array needs shifting of all its predecessors.

Linked list is the data structure which can overcome all the limitations of an array.
linked list is useful because,
• It allocates the memory dynamically. All the nodes of linked list are non-contiguously
stored in the memory and linked together with the help of pointers.
• Sizing is no longer a problem since we do not need to define its size at the time of
declaration. List grows as per the program's demand and limited to the available
memory space.
Types of linked list :
There are 4 different implementations of Linked List available, they are:
1. Singly Linked List
2. Doubly Linked List
3. Circular Linked List
4. Two way circular linked list

1. Single Linked List :


Single linked lists contain nodes which have a data part as well as an address part i.e.
next, which points to the next node in the sequence of nodes.
The operations we can perform on singly linked lists are insertion, deletion and
traversal.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
struct node
{
int data;
struct node *next;
};
struct node *start,*n1,*n2,*n3;
start=(struct node*)malloc(sizeof(struct node));
n1=(struct node*)malloc(sizeof(struct node));
n2=(struct node*)malloc(sizeof(struct node));
n3=(struct node*)malloc(sizeof(struct node));
n1->data=3;
n2->data=10;
n3->data=2; printf("%d",*start->next);
start->next=n1; printf("%d",*n1->next);
n1->next=n2; printf("%d",*n2->next);
n2->next=n3; getch();
}
2. Doubly linked list(two way linked list) :
In doubly linked list each node has two link field. Next pointer field contains the address
of the next node in the list and previous pointer contains the address of the previous
node in the list.

Syntax :
struct node
{
struct node *prev;
int data;
struct node *next;
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> printf("%d",*start->next);
struct node printf("%d",*n1->next);
{ printf("%d",*n2->next);
int data; printf("%d",*n2->prev);
struct node *next; printf("%d",*n3->prev);
Struct node *prev;
}; getch();
void main() }
{
struct node *start,*n1,*n2,*n3;
start=(struct node*)malloc(sizeof(struct node));
n1=(struct node*)malloc(sizeof(struct node));
n2=(struct node*)malloc(sizeof(struct node));
n3=(struct node*)malloc(sizeof(struct node));
n1->data=1;
n2->data=2;
n3->data=3;
start->next=n1;
n1->next=n2;
n2->next=n3;
n2->prev=n1;
n3->prev=n2;
3. Circular linked list:
A circular linked list is a singly linked list in which link field of the last node contains
the address of the first node of the list, instead of NULL. With this type of arrangement,
the coupling between each and every elements of the list becomes cyclic.
one two three
Data Next Data Next Data Next

#include<stdio.h> void main() one->next=two;


#include<conio.h> { two->next=three;
#include<stdlib.h> struct node *one,*two,*three; three->next=one;
one=malloc(sizeof(struct node));
struct node two=malloc(sizeof(struct node)); printf(“%d\t”,*one->next);
{ three=malloc(sizeof(struct node)); printf(“%d\t”,*two->next);
int data; printf(“%d”,*three->next);
struct node *next; one->data=1; getch();
}; two->data=2; }
three->data=3;

Result : 1 2 3
4. Two way Circular linked list:
A circular linked list is a doubly linked list in which we have two link fields the last node
contains the address of the first node and the first node contain address of the last node
of the list, instead of NULL. With this type of arrangement, the coupling between each
and every elements of the list becomes cyclic.
one two three
Prev Data Next Prev Data Next Prev Data Next

#include<stdio.h> void main() one->next=two;


#include<conio.h> { two-->three=three;
#include<stdlib.h> struct node *one,*two,*three; three->next=one;
one=malloc(sizeof(struct node)); one->prev=three;
struct node two=malloc(sizeof(struct node)); two->prev=one;
{ two=malloc(sizeof(struct node)); three->prev=two;
int data; printf(“%d\t”,*one->next);
struct node *next; one->data=1; printf(“%d\t”,*two->next);
struct node *prev; two->data=2; printf(“%d”,*three->next);
}; three->data=3; printf(“%d\t”,*one->prev);
printf(“%d\t”,*two->prev);
printf(“%d”,*three->prev);
Result : 1 2 3 3 1 2
getch();
}
Algorithm :
An algorithm is a step by step solution of any problem. In other words, an algorithm is a
procedure for solving problems. In order to solve a mathematical or computer problem.
An algorithm include calculations, reasoning and data processing.

Example:
1. Write an algorithm to add two numbers entered by user.

Step 1:
start
Step 2:
declare variables n1, n2 and sum.
Step 3:
read values n1and n2.
Step 4:
add n1 and n2 and assign the result to the sum.
Sum<-n1+n2;
Step 5: display sum
Step 6: stop
2. Write an algorithm to find the largest number among three different numbers
entered by user.

Step 1: start
Step 2: declare variables a, b and c.
Step 3: read variables a, b and c.
Step 4:
if(a>b)
If(a>c)
Display a is the largest number
else
Display c is the largest number.
else
If(b>c)
Display b is the largest number.
else
Display c is the largest number.
Step 5: stop
Flowchart :
A flowchart is the graphical representation of an algorithm with the help of different
symbols, shapes and arrows in order to define process of a program.

Symbols :

1. Terminal box(start/end) : Oval

2. Input/output : parallelogram

3. process/instruction : rectangle

diamond
4. Decision :

5. connector/Arrow : Line connectors


Example : print 1 to 20
Step 1: start
Step 2 : declare and initialize variable x as 0.
Step 3 : increment x by 1. Start
Step 4 : print x.
Step 5 : if x is less then 20 then go back to step2.
Step 6 : stop. Initialize x=0
Flowchart :

Increment x by 1

true Print x

X<20

false
End
Flow chart of simple if statement :

true
condition

false Code inside if body

Code after if body


Flow chart of If-else :
Flow chart of If-else-if :

You might also like