Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C Programming

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

C PROGRAMMING

Introduction
 C is a general purpose structured programming language. It is one of the most popular
programming languages.
 C was invented and first implemented by Dennis Ritchie on a DEC PDP-II (Digital Equipment
Corporation Programmed Data Processor-II) machine using UNIX operating system in early
1970’s.
 C was the result of a development process which started with an older language BCPL (Basic
Combined Programming Language) developed by Martin Richards. BCPL influence a
language called B which was invented by Ken Thompson and which led to development of C.

Features of C
 C is a general purpose programming language. C was originally developed for systems
programming. But, later is also used for writing commercial as well as scientific applications.
 C is a structured programming language. C provides fundamental flow control constructs
required for well structured programs. It allows developing well-defined, portable and easy to
maintain programs.
 C is a middle level language because it combines the elements of high level language with the
functionalities of an assembly language.
 C is a portable and efficient language. C programs written for one computer can be executed on
another with little or no modifications. C programs can be easily ported to new hardware or
operating system or both.
 C is a modular language. We can break down the program into functional units, develop
independent code and then, integrate them to make a complete application. The different
modules can be present in different files and can be compiled separately, thereby facilitating
team participation in the development.
 C allows code reusability. Besides the standard C function library, a programmer can create his
own functions and use them over and over again in different applications.

/* C program to display a welcome message */


#include<stdio.h>
main()
{
printf(“Welcome to C Programming”);
}

C Program Structure
a) Function Definition
 Every C program is divided into units called functions. A Function is a set of instructions
aimed at achieving a predefined goal or objective.
 Every C program must have main() from where the execution starts.
 The function body comprises or two parts- variable declarations and executable statements. All
the variables required in the function must be declared before any executable statement.
b) Delimiters
 All the statements belonging to a particular block or a function are placed between the opening
brace ‘{‘ and closing brace ‘}’.
c) Statement Terminator
 Every statement in a C program is terminated with a semi colon (;)
d) Standard C library
 All C compilers use as their first phase of compilation - a pre-processor, which performs
various manipulations on the source file before actually it is compiled.
 Pre-processor directives are not actually a part of C program, but rather instructions from us to
the compiler.
 The #include directive tells the pre-processor to read-in another file and include it in our
program. The most commonly required header file is ‘stdio.h’ which provides standard
input/output library functions. All header files end with .h extension.
e) Comment lines
 Any comment in a C program is placed between ‘/*’ and ‘*/’.
 Comments are not the party of the execution of the program.

/* C program to display address on the screen */


#include<stdio.h>
main()
{
printf(“\n A K N U MSN Campus”); /* \n is new-line escape sequence */
printf(“\n Acchampeta Junction \n Thimmapuram Post”);
printf(“\n Kakinada \n 533005”);
}

/* C program to store a value in the memory and display */


#include<stdio.h>
main()
{
int n=100; /* int is a data type. n is a variable */
printf(“\n Value stored in n is %d”,n); /* %d is a format specifier for integer */
}

Variable
A Variable is a named memory location where a value is stored. The value stored in the variable can
be changed during the execution of the program. The memory locations are identified by naming them
and these names are called as identifiers.
Rules for writing Variable names
 A variable name can be made of A-Z, a-z, 0-9 and underscore ( _ ). Other than these, no
characters and symbols are allowed to write variable names.
Eg: a, xyz, sum, s123,K_5... are valid
a-b,a*bc, sum of numbers .. are invalid
 The first character in the variable must start with an alphabet, not with a numeral.
Eg: 1ab, 123,1_ab .. are invalid
 All variable names are case sensitive.
Eg: ABC, abc, Abc, ABc, .. are different from each other
 Keywords (Reserved Words), which have a special meaning in C language cannot be used as
variable names. C provides 32 keywords. They are
int char float double unsigned signed long short
const if else switch case default for while
do auto static extern register break continue goto
struct union enum return volatile sizeof typedef void

Data Type
The data type of a variable specifies the type of value a variable can store. C provides four basic data
types – int, char,, float and double
Data Type Memory(in bytes) Storage
int 2 Integers
char 1 Single Character
float 4 Decimal numbers up to 6 digits of precision
Double 8 Decimal numbers up to 14 digits of precision

/* C program to assign two values and display*/


main()
{
int i=10,j=20;
printf(“\nValue in i=%d \n Value in j=%d”,i,j);
}

Modifiers
Modifiers are used to alter the meaning of the basic data type to fit for various situations more
precisely. They are short/long, signed/unsigned.
Type Size(in bits) Range
char or signed char 8 -128 to 127
unsigned char 8 0 to 255
short int or signed short int or int or signed int 16 -32768 to 32767
unsigned int or unsigned short int 16 0 to 65535
long int ot signed long int 32 -2147483648 to 2147483648
unsigned long int 32 0 to 4294967295
Float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932 to 3.4E+4932

Formatted Input / Output Statements


C allows to carryout Input / Output operations in a desired format. By formatted I/O, we can refer to an
input data that has to be arranged in particular format and output which would appear in a desired
format.
printf()
 printf() is a formatted output function which is used to display an output on the screen.
 Syntax:: printf(“format specifiers”[,<arg1>,<arg2>,...]);
 Format specifiers consists of
a) Characters that will be printed on the screen as they appear
b) Format specifications that define the output format for display of each item
c) Escape sequences
 arg1, arg2,... are the variables whose values are formatted and printed according to the
specifications given in the format specifiers.
scanf()
 scanf() is a formatted input function used to get an input from the user.
 Syntax:: scanf(“format specifiers”,<arg1>[,<arg2>,...]);
 Format specifiers states the data type for the variables to be read
 arg1, arg2,... specifies the address of the variable where the keyed-in data will be stored
 format specifiers contains a conversion character ‘%’ and a data type character or type
specifier.

/* program to read a number and display */


#include<stdio.h>
main()
{
int n;
printf(“\n Enter a number”);
scanf(“%d”, &n);
printf(“Value stored in n:%d”,n);
}

Format Specifiers
Format Specifiers determines the data type for the variable that is used in printf() and scanf()
statements. They are
Code Description Code Description
%c Single Character %s Group of Characters(String)
%d Decimal Integer %o Octal form
%x Hexa-Decimal form(lower case) %X Hexa-Decimal form(Upper case)
%f Signed floating point numbers %e Signed exponent notation(lower case)
%E Signed exponent notation %g,%G Most compact form of e, E, f
(Upper Case)
%u Unsigned decimal short int %U Unsigned decimal long int

Additional Modifiers
h -> for short int used along with d, i, o, x, X eg: %hd, %hi, ...
l -> for long int used along with d, i, o, x, X eg: %ld, %o, ...
for unsigned long int used long with U eg: %lU
for double used along with e, E, f, g, G eg: %le, %lE, %lg ...
L -> for long double used along with e, E, f, g, G eg: %le, %LE, %LG ...

/* C program to demonstrate format specifiers */


main()
{
int m=140;
float n=12.345;
printf(“m in decimal form:%d”,m);
printf(“m is octal form:%o”, m);
printf(“m in hexa-decimal form:%X”,m);
printf(“n in floating notating notation:%f”,n);
printf(“n in scientific notation: %e”,n);
}
Escape Sequence
Escape sequence is the name given to back-slash (\) constants that are available in C and are used to
format the output.
Constant Description Constant Description
\n New line character \r Carriage return
\b Back space \’ Single quote
\” Double quote \0 NULL
\t Horizontal tab \v Vertical tab
\\ Back-slash \? Question mark
\a Alert

/* C program to demonstrate escape sequences*/


manin()
{
printf(“Welcome”);
printf(“\n to”);
printf(“\t C \t programming”);
printf(“\nkakinada\b\b\bADA\a\a\a”);
}

Unformatted Input / Output Functions


C provides unformatted I/O functions which are used to carry out Input/output operations respectively
Function Description
getchar() Reads a character from keyboard with echo and waits for carriage return
getche() Reads a character from keyboard with echo and doesn’t wait for carriage return
getch() Reads a character from keyboard without echo and doesn’t wait for carriage return
putchar() Outputs a character to the text window on the screen
gets() Reads a string from keyboard
puts() Writes a string to standard output

/*C program to read and display a character using unformatted I/O functions*/
main()
{
char ch;
puts(“Enter a character:”);
ch=getchar();
putchar(ch);
puts(“Enter a character:”);
ch=getche();
putchar(ch);
puts(“Enter a character:”);
ch=getch();
putchar(ch);
}

Operators in C
C Provides potent set of operators to perform different operations. Operators act upon operands to
produce desired results.
Eg: c= a + b is an expression in which a, b, c are operands and =, + are operators.
Assignment Operator (=): The assignment operator ‘=’ is used to assign values to variables. The
value on the right side of the operator is assigned to the variable on its left.
Eg: pi=3.14; b=3+a; x=y+z;

Unary Operators: Unary operators act upon single operand.


- Unary Minus Negates the value of the operand
++ Unary Increment Increments the value by 1
- Unary Decrement Decrements the value by 1

/* Program to demonstrate unary operators */


main() Output
{
int a=10,b;
printf(“\na=%d”,a); a= 10
a=-a;
printf(“\na=%d”,a); a= -10
a=-a;
printf(“\na=%d”,a); a= 10
a++;
printf(“\na=%d”,a); a= 11
++a;
printf(“\na=%d”,a); a= 12
b=a++;
printf(“\na=%d b=%d”,a,b); a=13 b=12
b=++a;
printf(“\na=%d b=%d”,a,b); a=14 b=14
}

Pre-Increment Post Increment


Increment the value and then assign Assign the value and the increment
b=++a b=a++
a=a+1 b=a;
b=a a=a+1
Note: Same is applicable for pre-decrement and post decrement

Binary Operators
Binary operators act upon two operands
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division (remainder)

/*program to read two numbers and find their /*program to find the area and perimeter of
sum */ rectangle */
main() main()
{ {
int a,b,s; int l,b,p,a;
printf(“Enter two numbers:”); printf(“Enter length and breadth:”);
scanf(“%d%d”,&a,&b); scanf(“%d%d”,&l,&b);
s=a+b; a=l*b;
printf(“Sum=%d”,s); p=2*(l+b);
} printf(“Area=%d Perimeter=%d”,a,p);
}
/*program to find the area and perimeter of /*program to find the area and circumference of a
square */ circle */
main() main()
{ {
int s,p,a; float r,a,c;
printf(“Enter side:”); const float pi=3.14;
scanf(“%d”,&s); printf(“Enter radius of circle:”);
a=s*s; scanf(“%f”,&r);
p=4*s; a=pi*r*r;;
printf(“Area=%d Perimeter=%d”,a,p); c=2*pi*r;
} printf(“Area=%f Circumference=%f”,a,c);
}
/*program to find the volume of a cuboid */ /*program to find the area of triangle */
main() main()
{ {
float l,b,h,v; float b,h,a;
printf(“Enter length breadth height of a cuboid:”); printf(“Enter base and height of triangle:”);
scanf(“%f%f%f”,&l,&b,&h); scanf(“%f%f”,&b,&h);
v=l*b*h; a=1/2*b*h;
printf(“Volume=%f”,v); printf(“Area=%f”,a);
} }
/*program to find the volume of a cube */ /*program to find Simple Interest */
main() main()
{ {
float s,v; float p,r,t,si;
printf(“Enter side of a cube:”); printf(“Enter Principle Rate and Time:”);
scanf(“%f”,&s); scanf(“%f%f%f”,&p,&r,&t);
v=s*s*s; si=p*t*r/100;
printf(“Volume=%f”,v); printf(“Simple Interest=%f”,v);
} }

Constant
To assign a value to a variable that cannot be changed during the execution of the program, precede its
definition with a keyword ‘const’ . Syntax:: const type variable=value;
Eg; const int i=10; const float pi=3.14; const char ch=’c’;

/* Program to swap two numbers */

/* Using Temporary variable */ /* Without using Temporary /* Using Bitwise Operators */


main() variable */ main()
{ main() {
int a,b,temp; { int a,b;
printf(“Enter two numbers:”); int a,b; printf(“Enter two numbers:”);
scanf(“%d%d”,&a,&b); printf(“Enter two numbers:”); scanf(“%d%d”,&a,&b);
printf(“\n Before Swapping scanf(“%d%d”,&a,&b); printf(“\n Before Swapping
a=%d b=%d”,a,b); printf(“\n Before Swapping a=%d b=%d”,a,b);
temp=a; a=%d b=%d”,a,b); a=a^b;
a=b; a=a+b; b=a^b;
b=temp; b=a-b; a=a^b;
printf(“\n After Swapping a=a-b; printf(“\n After Swapping
a=%d b=%d”,a,b); printf(“\n After Swapping a=%d b=%d”,a,b);
} a=%d b=%d”,a,b); }
}
/*program to read two non-zero numbers and perform all arithmetic operations */
main()
{
int a,b,;
printf(“Enter two non-zero numbers:”);
scanf(“%d%d”,&a,&b);
printf(“Sum=%d”,a+b);
printf(“Difference=%d”,a-b);
printf(“Product=%d”,a*b);
printf(“Quotient=%d”,a/b);
printf(“Remainder=%d”,a%b);
}

Relational Operators
Relational operators are used to compare two quantities. Comparison is made to take a certain decision
depending upon the relationship between two quantities.
An expression containing a relational operator is known as relational expression. It always evaluate to either
true (non-zero) or false (zero).

== Equal to != Not equal to


< Less than <= Less than or equal to
> Greater than >= Greater than or equal to

Logical operators
Logical operators are used to combine two or more relational expressions into one relational expression. An
expression of this kind which combines two or more relational expressions is termed as logical expression or
compound relational expression. Similar to simple relational expression, the logical expression also evaluates to
either true (non-zero) or false (zero)

1. && - Logical AND 2. || - Logical OR 2. ! - Logical NOT

Ternary Operator
Ternary operator is also known as Conditional Operator. This operator takes the form
Syntax:: <expression 1> ? <expression 2> : <expression 3>
Here, upon evaluation of expression 1, if the result is true, expression 2 is evaluated. Otherwise expression 3 is
evaluated.

/* program to check whether the given number is less /* program to check whether the given number
than 100 or not */ is Even or Odd */
main() main()
{ {
int n; int n;
printf(“\n enter a number:”); printf(“\n enter a number:”);
scanf(“%d”, &n); scanf(“%d”, &n);
n<100?printf(“Given number is less than 100”) : n%2==0?printf(“Given number EVEN”):
printf(“Given number is not less than 100”); printf(“Given number is ODD”);
} }
/* program to find the biggest of three different /* program to find the smallest of five numbers
numbers */ */
main() main()
{ {
int a,b,c; int a,b,c,d,e;
printf(“\n enter three different numbers:”); printf(“\n enter five different numbers:”);
scanf(“%d%d%d”, &a,&b,&c); scanf(“%d%d%d%d%d”, &a,&b,&c,&d,&e);
a>b && a>c ? printf(“%d is big”,a): b>c ? printf(“%d is a=a<b?a:b;
big”,b):printf(“%d is big”,c); a=a<c?a:c;
} a=a<d?a:d;
a=a<e?a:e;
printf(“Small=%d”,a);
}

Comma Operator
It can be used to link the related expressions together. A comma-linked list of expressions is evaluated left to
right. The value of the right most expression is the value of the combined expression.
Eg: in a, b, c;
c = (a=10, b=20,a+b); /* c is assigned with value 30 */

sizeof operator
It is used to return the size of operand in bytes

/*Program to demonstrate sizeof operator */


main()
{
int i=10;
printf(“Value in i=%d Size of i in bytes=%d”, i,sizeof(i));
printf(“Size of float in bytes is %d”, sizeof(float);
}
Constructs
Constructs are the building blocks of statements which are used to increase the efficiency of the program.
C provides two types of constructs – a) Selection Constructs b) Iteration or Looping Constructs

i) Selection Constructs
Selection Constructs are used whenever a selective part of the code is to be executed. C provides two types of
selection constructs a) if b) switch .. case

if constructs
The ‘if’ statement is used to test the validity of condition
Syntax: if(<condition>)
{
Statements;
}
In the above syntax, if the condition that is placed within the parenthesis is true, the set of statements placed
under it within the braces are executed. Otherwise, those statements are skipped and the control jumps to next
statement after the closing brace.

/*Program to check whether a given number is less than 100 */


main()
{
int i;
printf(“Enter a number:”);
scanf(“%d”,&i);
if(i<100)
{
printf(“Given number is less than 100”);
}
}
if...else
It is second form of ‘if’
Syntax: if(<condition>)
{
Statements;
}
else
{
Statements;
}

In the above syntax, if the condition is true, the statements written under the ‘if’ block is executed. Otherwise,
the statements written under ‘else’ block is executed.

/*Program to check whether a given number is less /*Program to check whether a given number is
than 100 or not */ EVEN or ODD */
main() main()
{ {
int i; int i;
printf(“Enter a number:”); printf(“Enter a number:”);
scanf(“%d”,&i); scanf(“%d”,&i);
if(i<100) if(i%2==0)
{ {
printf(“Given number is less than 100”); printf(“Given number is EVEN”);
} }
else else
{ {
printf(“Given number is not less than 100”); printf(“Given number is ODD”);
} }
} }
/*Program to read two different numbers and find /*Program to read two different numbers and find
the smallest */ whether first number is factor of second number */
main() main()
{ {
int i,j; int i,j;
printf(“Enter two different numbers:”); printf(“Enter two non-zero numbers:”);
scanf(“%d%d”,&i,&j); scanf(“%d%d”,&i,&j);
if(i<j) if(j%i==0)
{ {
printf(“%d is smallest”,i); printf(“%d is a factor of %d”,i,j);
} }
else else
{ {
printf(“%d is smallest”,j); printf(“%d is not a factor of %d”,i,j);
} }
} }

/*Program to read two numbers and find the quotient and remainder */
main()
{
int i,j;
printf(“Enter two different numbers:”);
scanf(“%d%d”,&i,&j);
if(j==0)
{
printf(“Division not possible”);
}
else
{
printf(“Quotient=%d Remainder=%d”,i/j, i%j);
}
}

nested if
An ‘if’ construct can be nested in another ‘if’ as follows

Syntax: if(<condition>)
{
---
if(<condition>)
{
---
}
else
{
---
}
---
}
else
{
---
if(<condition>)
{
---
}
else
{
---
}
---
}

else... if ladder
The ‘else..if’ ladder is used when multiple path decisions are involved. A multi path decision is a chain of ‘if’
statements where all the ‘else’ clause is followed by another ‘if’ statement.

Syntax: if(<codition>)
{
Statements;
}
else if(<condition>)
{
Statements;
}
---
else
{
Statements;
}
/* Program o compare two numbers */ /* Program to find biggest of three different
main() numbers */
{ main()
int a,b; {
printf(“\n Enter two numbers:); int a,b,c;
scanf(“%d%d”,&a,&b); printf(“\n Enter three numbers:);
if(a>b) scanf(“%d%d%d”,&a,&b,&c);
printf(“% is greater than %d”,a,b); if(a>b && a>c)
else if(a<b) printf(“%d is big”,a);
printf(“% is less than %d”,a,b); else if(b>c)
else printf(“% is big”,b);
printf(“% is equal to %d”,a,b); else
} printf(“%d is big”,c)
}

/*Program to perform arithmetic operation based on the choice entered */

main() main()
{ {
int a,b,ch; int a,b;
printf(“\n Enter two numbers:”); char ch;
scanf(“%d%d”,&a,&b); printf(“\n Enter two numbers:”);
printf(“\n1. Addition \n 2.Subtraction \n scanf(“%d%d”,&a,&b);
3.Multiplication \n 4.Division \n 5.Modulo Division”); printf(“\n Addition \n Subtraction \n Multiplication
printf(“\n\n Enter your choice:”); \nDivision \n Modulo Division”);
scanf(“%d”,&ch); printf(“\n\n Enter your choice A S M Q R:”);
ch=getche();
if(ch==1)
printf(“Sum=%d”,a+b); if(ch==’A’ || ch==’a’) /*if(toupper(ch)==’A’) */
else if(ch==2) printf(“Sum=%d”,a+b);
printf(“Difference=%d”,a-b); else if(toupper(ch)==’S’)
else if(ch==3) printf(“Difference=%d”,a-b);
printf(“Product=%d”,a*b); else if(toupper(ch)==’M’)
else if(ch==4) printf(“Product=%d”,a*b);
{ else if(toupper(ch)==’Q’)
if (b==0) {
printf(“Division not possible with zero”); if (b==0)
else printf(“Division not possible with zero”);
printf(“Quotient=%d”,a/b); else
} printf(“Quotient=%d”,a/b);
}
else if(ch==5) else if(toupper(ch)==’R’)
{ {
if (b==0) if (b==0)
printf(“Division not possible with zero”); printf(“Division not possible with zero”);
else else
\ printf(“Remainder=%d”,a%b); \ printf(“Remainder=%d”,a%b);
} }
else else
printf(“Invalid Choice”); printf(“Invalid Choice”);
} }
switch .. case construct
It is a multi-way decision construct that tests whether the expression matches one of the number of constant
values and branches the control accordingly.

Syntax:: switch(< expression>)


{
case <constant 1>: statements;
break;
case <constant 2>: statements;
break;
---
case <constant n>: statements;
break;
default : statements;
}
In the above syntax, expression is an integer (or) a character variable. It can’t contain any relational or logical
expressions.
‘break” statement is used with switch.. case to indicate the end of particular case and causes an exit from the
switch block, transferring the control to the statement immediately after the switch statement block.

/* Program to display the name of the week basing /*Program to check whether a given character is
on the weekday number */ vowel or not */
main() main()
{ {
int n; char ch;
printf(“Enter the weekday number:”): printf(“Enter a character:”);
scanf(“%d”, &n) ch=getche();
switch(n) switch(toupper(ch))
{ {
case 1: printf(“MONDAY”); case ‘A’:
break; case ‘E’:
case 2: printf(“TUESDAY”); case ‘I’:
break; case ‘O’:
case 3: printf(“WEDNESDAY”); case ‘U’:printf(“Vowel”);
break; break;
case 4: printf(“THURSDAY”); default: printf(“Not a vowel”);
break; }
case 5: printf(“FRIDAY”); }
break;
case 6: printf(“SATURDAY”);
break;
case 7: printf(“SUNDAY”);
break;
default: printf(“Invalid choice”);
}
}
/*Program to perform arithmetic operation based /* Program to display the number od days of a
on the choice entered */ month */
main() #include<stdio.h>
{ #include<conio.h>
int a,b,ch;
void main()
printf(“\n Enter two numbers:”);
{
scanf(“%d%d”,&a,&b);
printf(“\n1. Addition \n 2.Subtraction \n int m,y;
3.Multiplication \n 4.Division \n 5.Modulo Division”); printf("\n Enter the month No.:");
printf(“\n\n Enter your choice:”); scanf("%d",&m);
scanf(“%d”,&ch); if(m==2)
switch(ch) {
{ printf("\nEmter year:");
case 1:printf(“Sum=%d”,a+b); scanf("%d",&y);
break;
if(y%4==0 && y%100!=0 || y%400==0)
case 2:printf(“Difference=%d”,a-b);
printf("Leap Year. No. of days=29");
break;
case 3:printf(“Product=%d”,a*b); else
break; printf("Non-Leap Year. No. of days=28");
case 4: if (b==0) }
printf(“Division not possible with zero”); else
else {
printf(“Quotient=%d”,a/b); switch(m)
break; {
case 5: if (b==0) case 1:
printf(“Division not possible with zero”); case 3:
else
case 5:
printf(“Remainder=%d”,a%b);
case 7:
default:printf(“Invalid Choice”);
} case 8:
} case 10:
case 12:printf("No. of days=31");
break;
case 4:
case 6:
case 9:
case 11:printf("No. of days=30");
break;
default:printf("Invalid number");
}
}
getch();
}

Iteration Constructs
Iteration means repeation. In ‘C’ language, iteration constructs are used to repeat a block of
statement(s) for a certain number of times or until a condition is met. Iteration constructs are also
called as looping constructs. In looping, a sequence of statements is executed util some condition for
the termination of loop is satisfied. C provides three types of looping constructs – for, while, do..while.

for construct
for is used when we want to execute a loop for a fixed number of times.
Syntax:: for(initialization; condition checking; re-evaluation parameters)
{
Statements;
}
 The initialization part usually consists of an assignment that is done before the execution of the
loop.
 The loop is executed as long as the condition is true
 The re-evaluation parameter is an assignment expression that increase or decreases the value
of the loop counter
 The three expressions in the loop are separated by semi-colon(;)
/* Program to display a string 10 times */ /* Program to display a first 10 natural
main() numbers */
{ main()
int i; {
for(i=1;i<=10;i++) int i;
{ for(i=1;i<=10;i++)
printf(“\n C programming”); {
} printf(“%4d”, i));
} /* %4d leaves 4 spaces between each output */
}
}
/* Program to display a first n natural /* Program to display all even numbers below
numbers */ 100 */
main() main() main()
{ { {
int i,n; int i; int i;
printf(“Enter value of n:”); for(i=1;i<100;i++) for(i=2;i<100;i+=2)
scanf(“%d”,&n); if(i%2==0) printf(“%4d”,i);
for(i=1;i<=n;i++) printf(“%4d”,i); }
{ } }
printf(“%4d”, i)); }
}
}
/* Program to display the multiplication table /* Program to display all ODD numbers below
of a given number up to a given range*/ 100 in reverse order */
main()
{ main() main()
int n,m,i; { {
printf(“Enter number & range”); int i; int i;
scanf(“%d%d”,&n,&m); for(i=99;i>0;i--) for(i=99;i>100;i-=2)
for(i=0;i<=m;i++) if(i%2!=0) printf(“%4d”,i);
printf(“\n%d * %d = %d”,n,i,n*i); printf(“%4d”,i); }
} } }
}
/* Program to count the number of factors of a /* Program to display the factors of a given
given number*/ number*/
main() main() main() main()
{ { { {
int n,i,c=0; int n,i,c=0; int n,i; int n,i;
printf(“Enter a printf(“Enter a printf(“Enter printf(“Enter
number:”); number:”); number:”); number:”);
scanf(“%d”,&n); scanf(“%d”,&n); scanf(“%d”,&n); scanf(“%d”,&n);
for(i=1;i<=n;i++) for(i=1;i<=n/2;i++) for(i=1;i<=n;i++) for(i=1;i<=n/2;i++)
if(n%i==0) if(n%i==0) if(n%i==0) if(n%i==0)
c++; c++; printf(“%d”,i); printf(“%d”,i);
printf(“Number of printf(“Number of } printf(“%d”,n);
factors=%d”,c); factors: %d”,c+1); }
} }

C’s shorthand way to right expressions


Variable operator=expression eg: n+=2 (n=n+2) n-=3 (n=n-3) n*=4 (n=n*4) n/=2 (n=n/2)
/* Program to check whether a given number is prime or not*/
main() main() main()
{ { {
int n,i,c=0; int n,i,c=0; int n,i,c=0;
printf(“Enter number:”); printf(“Enter number:”); printf(“Enter number:”);
scanf(“%d”,&n); scanf(“%d”,&n); scanf(“%d”,&n);
for(i=1;i<=n;i++) for(i=1;i<=n/2;i++) for(i=2;i<=n/2;i++)
if(n%i==0) if(n%i==0) if(n%i==0)
c++; c++; {
if(c==2) if(c==1) c++;
printf(“PRIME NUMBER””); printf(“PRIME NUMBER””); break;
else else }
printf(“NOT A PRIME printf(“NOT A PRIME if(c==0)
NUMBER”); NUMBER”); printf(“PRIME NUMBER”);
} } else
printf(“NOT A PRIME
NUMBER”);
}

‘break’
break statement is not only used in switch-case construct but also in looping a construct so as to break
a loop and come out of the loop to the next statement after the construct, not allowing further
iterations.
/* Program to check whether a /*Program to find the sum of /*Program to find the sum of
given number is perfect first 10 natural numbers */ 10 different numbers */
number or not */ main() main()
main() { {
{ int i,sum=0; int n,i,sum=0;
int n,i,c=0; for(i=1;i<=10;i++) for(i=1;i<=10;i++)
printf(“Enter number:”); sum+=i; {
scanf(“%d”,&n); printf(“SUM of forst 10 printf(“\n Enter a number:”);
for(i=1;i<=n/2;i++) numbers is %d”,sum); scanf(“%d”,&n);
if(n%i==0) } sum+=n;
c+=i; }
if(c==n) printf(“SUM =%d”,sum);
printf(“PERFECT NUMBER”); }
else
printf(“NOT A PERFECT
NUMBER”):
}

Nested for
A ‘for’ construct can be nested in another ‘for’ construct as follows
for(...) /* outer for */
{
---
for(---) /*inner for */
{
---
}
---
}
In such case, the control will go to the next iteration of the outer for once it completes the iterations of
inner for. For the next iteration of outer for, the inner for is executed again and the same process is
continued till all the iterations of the outer for are completed.

/* Programs to display the following outputs */

a) 11111 b) 12345 c) * c) *
22222 23456 ** **
33333 34567 *** ***
44444 45678 **** ****
55555 56789 ***** *****
main() main() main() main()
{ { { {
int i,j; int i,j; int i,j; int i,j,k;
for(i=1;i<=5;i++) for(i=1;i<=5;i++) for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ { { {
for(j=1;j<=5;j++) for(j=i;j<=i+4;j++) for(j=1;j<=i;j++) for(j=1;j<10-i;;j++)
printf(“%d ”,i); printf(“%d ”,j); printf(“* ”,i); printf(“ “);
printf(“\n”); printf(“\n”); printf(“\n”); for(k=1;k<=i;k++)
} } } printf(“* ”);
} } } printf(“\n”);
}
}

/* program to display the factors of a numbers /* program to print all prime numbers below
from 1 to a given number */ 100*/
main() main()
{ {
int i,j,n; int n,i,c;
printf(“\n Enter a number:”); for(n=2;n<100;n++)
scanf(“%d”,&n); {
for(i=1;i<=n;i++) c=0;
{ for(i=2;i<=n/2;i++)
printf(“Factors of %d are:”,i); if(n%i==0)
for(j=1;j<=i./2;j++) {
if(i%j==0) c++;
printf(“%2d”,j); break;
printf(“%2d”,i); }
} if(c==0)
} printf(“%2d”,n);
}
}

Multiple initializations in for loop


It is allowed to initialize multiple variables in a ‘for’ loop using comma (,) operator. Also we can
separate multiple re-evaluation parameters using comma operator. But there should be a single
condition in ‘for’ loop. Multiple conditions are combined using logical operator.

/* program to get the following output


0 + 100 = 100 1 + 99 = 100 2 + 98 = 100 ... 99 + 1 = 100 100 + 0 = 100 */
/* Using multiple initializations */ /* Not using multiple initializations */
main() main()
{ {
int i,j; int i;
for(i=0,j=100;i<=100;i++,j--) for(i=0;i<=100;i++,j--)
printf(“%d + %d = %d\t”,i,j,i+j) printf(“%d + %d = 100\t”,i,100-i)
} }

Missing parameters in for loop


It is possible to construct ‘for’ loop with missing parameters.
/* Program to print first 10 numbers */

/*With all /* Missing initialization */ /* Missing re-evaluation


parameters*/ main() parameters */
main() { main()
{ int i=1; {
int i; for(;i<=10;i++) int i;
for(i=1;i<=10;i++) printf(“%d”,i); for(i=1;i<=10;)
printf(“%d”,i); } {
} printf(“%d”,i);
i++;
}
}
/*Missing condition*/ /*Missing initialization and re- /* Missing all parameters */
main() evaluation parameters */ main()
{ main() {
int i; { int i=1;
for(i=1;;i++) int i=1; for(;;)
{ for(;i<=10;) {
if(i>10) { if(i>10)
break; printf(“%d”,i); break;
printf(“%d”,i); i++; printf(“%d”,i);
} } i++;
} } }
}

‘continue’
The continue statement is used in loop so as to make the control jump to next iteration without further
processing the statements in the loop.

/* Program to display all numbers below 100 which are not multiples of 5 */
main()
{
int i;
for(i=1;i<100;i++) /* In the program, when the condition i%5==0 is true, the control jumps to the
{ nest iteration without executing the printf() statement in the for loop */
if(i%5==0)
continue;
printf(“%4d”,i);
}
}
‘while’ construct ‘do.. while’ construct
It is the simplest of looping constructs available to
In ‘do..while’ construct, the body of the loop is
a programmer in C. executed and then the condition is checked for
Syntax :: while(<condition>) next iteration. If the condition is true, the control
{ goes to the next iteration otherwise, terminates
Statements; from the loop.
} Syntax:: do
{
In this construct, the body of the loop is executed Statements;
only when the condition is true } while(<condition>);

/* Program to print first 10 numbers */ /* Program to print first 10 numbers */


main() main()
{ {
int i=1; int i=1;
while(i<=10) do
{ {
printf(“%4d”, i); printf(“%4d”, i);
i++; i++;
} } while(i<=10)
} }

Difference between while and do ..while


 while is a pre-test looping construct whereas do..while is a post-test looping construct.
 In while construct, the body of the loop is executed only when the condition is true whereas
under do..while construct, the body of the loop is executed first, and then the condition is
checked.
 In while construct, the number of times the body of the loop executes depends up on the
condition whereas in case of do..while, the body of the loop is executed at least once.

main() main()
{ {
int i=1; int i=11;
while(i<=10) do
{ {
printf(“%4d”, i); printf(“%4d”, i);
i++; i++;
} } while(i<=10)
printf(“\nEnd”); printf(“\nEnd”);
} }
Output: End Output: 11
End

/*Program to find the sum of digits of a given /*Program to find lucky number */
number */ main()
main() {
{ int n,r,s=0;
int n,r,s=0; printf(“\n Enter a Number:”);
printf(“\n Enter a Number:”); scanf(“%d”,&n);
scanf(“%d”,&n); while(n!=0).
while(n!=0) {
{ while(n!=0)
r=n%10; {
s=s+r; r=n%10;
n=n/10; s=s+r;
} n=n/10;
printf(“\nSum=%d”,s); }
} if(s>=10)
n=s;
}
printf(“\nSum=%d”,s);
}
/*Program to reverse a given number */ /*Program to check whether a given number is
main() palindrome or not */
{ main()
int n,r,s=0; {
printf(“\n Enter a Number:”); int n,t,r,s=0;
scanf(“%d”,&n); printf(“\n Enter a Number:”);
while(n!=0) scanf(“%d”,&n);
{ t=n;
r=n%10; while(n!=0)
s=s*10+r; {
n=n/10; r=n%10;
} s=s*10+r;
printf(“\nReverse of a given number=%d”,s); n=n/10;
} }
if (s==t)
printf(“\nNumber is PALINDROM”);
else
printf(“\nNumber is NOT A PALINDROM”);
}
/*Program to print nth Fibonacci numbers */ /*Program to print first n Fibonacci numbers
main() */
{ main()
int a=1,b=0,count=1,n; {
printf(“\nwhich fibo number you want:”); int a=1,b=0,count=1,n;
scanf(“%d”,&n); printf(“\nHow many numbers you want:”);
do scanf(“%d”,&n);
{ do
printf(“%d”,a); {
c=a+b; printf(“%d”,a);
b=a; c=a+b;
a=c; b=a;
count++; a=c;
}while(count <n) count++;
printf(“%d”,a); }while(count <=n)
} }
/*Program to check whether a given number is /*Program to find the GCD of two numbers */
Armstrong number or not */ main()
main() {
{ int a,b,r;
int n,t,r,s=0; printf(“\n Enter two non-zero numbers:”);
printf(“\n Enter a Number:”); scanf(“%d%d”,&a,&b);
scanf(“%d”,&n); do
t=n; {
while(n!=0) c=a%b;
{ if(c==0)
r=n%10; {
s=s+r*r*r; printf(“GCD=%d”,b);
n=n/10; exit(0);
} }
if (s==t) c=b;
printf(“\nNumber is ARMSTRONG”); b=c;
else }
printf(“\nNumber is NOT AN ARMSTRONG”); }
}
/*Program to print all palindrome numbers /*Program to print all armstrong numbers
below 1000 */ below 1000 */
main() main()
{ {
int n,t,r,s=0; int n,t,r,s=0;
for(n=1;n<1000;n++) for(n=1;n<1000;n++)
{ {
t=n t=n;
while(t!=0) while(t!=0)
{ {
r=t%10; r=t%10;
s=s*10+r; s=s+r*r*r;
t=t/10; t=t/10;
} }
if (s==n) if (s==n)
printf(“%5d”,n); printf(“%5d”,n);
} }
} }

exit() goto
The exit() is used to terminate from program The goto statement is used make the control jump
Syntax: exit(int); to a particular label in the program
/* Program to demonstrate exit() */ Syntax: goto <label name>;
main() /*Program to demonstrate goto */
{ main()
int a,b; {
printf(“Enter two numbers:”); int n,i;
scanf(“%d”%d”,&a,&b); printf(“\n Enter range:”);
if(b==0) scanf(“%d”,&n);
{ i=1;
printf(“Division not possible”); NUM:
exit(1); printf(“%d”,i++);
} if(i<=n)
printf(“Quotient=%d Remainder=%d”,a/b/a%b); goto NUM;
} }

Functions
A function is a set of programming statements aimed at achieving a desired task.
Syntax :: return_type function_name(parameter list)
{
/* Body of the function */
}
A function declaration in ‘C’ consists of a function name followed by a pair of parenthesis(). The
parenthesis can contain an optional list of parameters whose values are passed through a function call.
The body of the function is closed within braces.
A function can have an optional ‘return’ statement. The return type of a function specifies the type of
value that a function can return to the calling function.
Note: A function call is made as - function_name(<arguments>);
A function that invokes another function is called as a calling function. The function that being
invoked is termed as a called function.

Eg: main() Output:


{ In the main function
printf(“\n In the main function”); Calling function fun()
printf(“\n Calling function fun()”);
func(); In the fun()
printf(“\n\n Back to main”); Going back to main function
printf(“\n Again calling function fun()”);
func(); Back to main
printf(“\n\n Back to main”); Again calling function fun()
printf(“\nEnd”);
} In the fun()
fun() Going back to main function
{
printf(“\n\n In the fun()”); Back to main”
printf(“\n Going back to main function”); End
}

Types of functions
 C provides two types of functions namely In-built functions and User-defined functions.
 In-built functions, also known as Library functions, are available to a program in the standard
C library.
 User-defined functions are those functions that are written by the programmer to achieve
desired results.

Advantages of functions
 Functions are easy to define and use.
 Functions facilitate the modular programming technique.
 Functions can be used to divide large bulky program into functionally independent modules or
sub-programs that can be tested, debugged and maintained independently.
 The user-defined functions can be made a part of library which in turn facilitates the usage of
those functions across various other C programs. Thereby this feature saves the time of
writing the functions again.

Functions with arguments and no return value


/* Program to read a number in main() and /*Program to read two numbers and find their
display it in function */ sum*/
main() sum(int,int);
{ /*Function prototype. Function is global */
display(int); main()
/*Function prototype. Function is local to main */ {
int n; int a,b;
printf(“\n Enter a Number:”); printf(“\n Enter two numbers:”);
scanf(“%d”,&n); scanf(“%d%d”,&a,&b);
display(n); sum(a,b);
} }
display(int n) sum(int p,int q)
{ {
printf(“Entered value is %d”,n); int s=p+q;
} printf(“Sum = %d”,sum);
}

Function Prototyping
It is the process of declaring a function before actually defining it. In function prototype, we specify
the function name, its return-type and the parameters it takes. A prototype merely specifies the
function interface, not the body of the function.
Note: A calling function can send a package of values to the called function to operate on. Each value
passed to a function in such manner is known as argument.
Syntax :: function_name(<arg_1>,<arg_2>, ...);
There is no limitation to the number of arguments that are passed to a user-defined function and these
arguments are separated by commas.

Actual and Formal Arguments


 The data that is passed by a calling function as arguments is known as “Actual Arguments”.
 The names of the parameters in the called function are known as “Formal or Dummy
Arguments.” In the definition of called function, the formal parameters must be declared
separately.
Functions with arguments and return value
A ‘called function’ can send back a value to a ‘calling function’ using return statement.
Syntax: retrun (<expression>);
When a return statement is placed in a function, the control will immediately jumps back to the calling
function. Whatever is placed in the parenthesis is returned back to the calling function.
Types of return statement
return; No value is returned
return(<constant>); Specific value is returned Eg. return(100); return(‘a’);
retrun(<variable>); Value stored in the variable is returned Eg. retrun(sum);
retrun(<expression>); Value is returned up on evaluation Eg: retrun(a+b);
of expression retrun(a>b?a:b);

/*program to find maximum and minimum of }


two numbers */ int max(int p,int q)
main() {
{ int m;
int a,b,r; if(p<q)
printf(“\n Enter two numbers:”): return(p);
scanf(“%d%d”,&a,&b); else
r=max(a,b); return(q);
printf(“\n maximum of two numbers:%d”,r); }
printf(“\n minimum of two int min(int x,int y)
numbers:%d”,min(a,b)); {
retrun(x>y?x:y);
}
/*Program to perform arithmetic operations based add()
on the choice entered until users’ wish */ {
int a,b; printf(“\n Enter two numbers:”);
main() scanf(“%d%d”,&a,&b);
{ printf(“\nSum=%d”,a+b );
int ch; }
char c; sub()
do {
{ printf(“\n Enter two numbers:”);
printf(“\n1. Addition \n 2.Subtractio\n 3.Multiplication scanf(“%d%d”,&a,&b);
\n4.Division\n5.Modulo Division”);
printf(“\nDifference=%d”,a-b );
}
printf(“\n\n Enter your choice:”);
scanf(“%d”,&ch); mul()
{
switch(ch) printf(“\n Enter two numbers:”);
{ scanf(“%d%d”,&a,&b);
case 1: add(); printf(“\nProduct=%d”,a*b );
break; }
case 2: sub();
break; qut()
case 3: mul(); {
break; printf(“\n Enter two numbers:”);
case 4: qut(); scanf(“%d%d”,&a,&b);
break; if (b==0)
case 5: rem(); printf(“Division not possible with zero”);
break; else
case 0: exit(0); printf(“Quotient=%d”,a/b);
default:printf(“Invalid Choice”); }
} rem()
{
printf(“\n Do you want to continue Y/N:”);
printf(“\n Enter two numbers:”);
c=getche();
scanf(“%d%d”,&a,&b);
if (b==0)
}while(toupper(c)==’Y’);
printf(“Division not possible with zero”);
else
}
printf(“Remainder=%d”,a/b);
}

Local and Global Variables


A local variable is a variable that is declared within a function. It can be accessed only in the function
in which it is been decalred.
A global variable is a variable which is declared outside the function. it can be accessed in any part of
the program from the point of its declaration.

/*program to demonstrate local and global variables */


int n=50;
main() Output
{
int m=10;
printf(“\nm=%d n=%d”,m,n); m=10 n=50
fun1(m);
printf(“\nm=%d n=%d”,m,n); m=10 n=40
n=n+10;
m=fun2(m);
printf(“\nm=%d n=%d”,m,n); m=70 n=70
}
fun1(int m)
{
printf(“\nm=%d n=%d”,m,n); m=10 n=50
m=m+10;
n=n=10;
}
int fun2(int x)
{
printf(“\nx=%d n=%d”,x,n); x=10 n=50
x=x-5;
n=n+20;
return(n);
}

Arrays
An array is a collection of data elements of same type referenced by a common name. Elements are
called the members of the array. Each member is identified by the array name followed by unique
index which starts with zero.
Syntax: datatype arrayname[size];
Eg: int a[10];

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

Assignment of values to an array 1 2 3 4 5


int a[5]={1,2,3,4,5} a[0] a[1] a[2] a[3] a[4]

int a[]={1,2,3} 1 2 3
a[0] a[1] a[2]

int a[5]={1,2} 1 2 0 0 0
a[0] a[1] a[2] a[3] a[4]

/*Program to read 10 numbers into an array /*Program to read n numbers into an array
and display */ and display */
main() main()
{ {
int a[10],i; int a[30],i,n;
printf(“\n Enter 10 numbers:”); printf(“How many numbers you want to print:”);
for(i=0;i<10;i++) scanf(“%d”,&n);
{ printf(“\n Enter %d numbers:”,n);
printf(“\n Enter No:”); for(i=0;i<n;i++)
scanf(“%d”,&a[i]); {
} printf(“\n Enter No:”);
for(i=0;i<10;i++) scanf(“%d”,&a[i]);
printf(“%5d”,a[i]); }
} for(i=0;i<n;i++)
printf(“%5d”,a[i]);
}
/*Program to find sum of 10 numbers in an /*Program to find the maximum and minimum
array */ of 10 numbers in an array */
main() main()
{ {
int a[10],i,sum=0; int a[10],i,min,max;
printf(“\n Enter 10 numbers:”); printf(“\n Enter 10 numbers:”);
for(i=0;i<10;i++) for(i=0;i<10;i++)
{ {
printf(“\n Enter No:”); printf(“\n Enter No:”);
scanf(“%d”,&a[i]); scanf(“%d”,&a[i]);
sum=sum+a[i]; }
} min=max=a[0];
printf(“Sum = %d”,sum); for(i=0;i<10;i++)
} {
if(a[i]<min)
min=a[i];
else if(a[i]>max)
max=a[i];
}
printf(“Minimum=%d Maximum=%d”,min,max);
}
/*Program to read 10 characters into an array /* Program to find the sum of numbers in ODD
and display along with their ASCII values */ places and sum of numbers in even places */
main() main()
{ {
char a[10]; int a[10]={1,2,3,4,5,6,7,8,9,10},i,so=0,se=0;
int i;
printf(“\n Enter 10 characters:”); for(i=0;i<10;i++)
for(i=0;i<10;i++) {
{ if((i+1)%2==0)
printf(“\n Enter a character:”); so+=a[i];
a[i]=getche(); else
} se+=a[i];
for(i=0;i<10;i++) printf(“\nSum of odd Numbers: %d
printf(“%c --- %d”,a[i],a[i]); \nSum of even Numbers: %d”, so,se);
} }

String/Character Arrays
A string can be defined as character type array which is teriminated by a NULL character (‘\0’).
Note: Strings are the only character constants in C language that are enclosed in double quotes (“ ”).

/* Program to read a string and display */


main()
{
char str[20];
printf(“\n Enter a String :”);
gets(str); /*Accepts whitespace characters */
/* scanf(“%s”, str); Doesn’t accept whitespace characters */
/* scanf(“%[^\n]”, str); Accepts characters until enter is pressed */
printf(“Entered string is %s”,str);
}
 scanf() statement doesn’t recognise whitespace characters(enter, space & tab). So, though we
scan strings using scanf() with %s, it will accept string only before space, tab or enter in the
string.
 If scan() is used with %[^\n] , it will accept the string till enter is pressed.

/*Program to find the length of a given string*/ /*Program to copy the contents of one string
main() into another string */
{ main()
char str[20]; {
int len=0,i; char str1[20],str2[20];
printf(“\n Enter a string”); int i;
gets(str); printf(“\n Enter a string”);
for(i=0;str[i]!=’\0’;i++) gets(str1);
len++; for(i=0;str1[i]!=’\0’;i++)
printf(“Length of given string=%d”,len); str2[i]=str1[i];
} str2[i]=’\0’;
printf(“Copied String= %s”,str2);
}
/*Program to concatenate two strings */ /*Program to compare two string */
main() main()
{ {
char str1[20],str2[20]; char str1[20],str2[20];
int i,j; int i,i;
printf(“\n Enter two strings”); printf(“\n Enter two strings”);
gets(str1); gets(str1);
for(i=0;str1[i]!=’\0’;i++); for(i=0;str1[i]==str2[i] && str1[i]!=’\0’;i++);
for(j=0;str[j]!=’\0’,j++,i++) if(str1[i]<str2[i])
str1[i]=str2[j]; printf(“\n str1 is less than str2”);
str1[i]=’\0’; else if(str1[i]>str2[i])
printf(“Concatenated String= %s”,str1); printf(“\n str1 is greater than str2);
} else
printf(“Both are equal”);
}
/* Program to reverse a given string */ /* Program to check whether a given string is
main() palindrome or not */
{ main()
char str[20],ch; {
int len,i,m; char str[20],ch;
printf(“\n Enter a string”); int len,i,m;
gets(str); printf(“\n Enter a string”);
printf(“\nBefore reverseing: %s”,str); gets(str);
for(len=0;str[len]!=’\0’;len++); printf(“\nBefore reverseing: %s”,str);
m=len/2; for(len=0;str[len]!=’\0’;len++);
len--; m=len/2;
for(i=0;i<m;i++,len--) len--;
{ for(i=0;i<m;i++,len--)
ch=str[i]; {
str[i]=str[len]; if(str[i]!=str[len]
str[len]=ch; {
} printf(“\n Not a palindrome”);
printf(“\nAfter reverseing: %s”,str); exit(0);
} }
}
printf(“\nPalindrom”);
}
/* Program to find the occurrence of a /* Program to find the occurrence of a sub-
character in a given String */ string in a given String */
main() #include<stdlib.h>
{ main()
char str[20],ch; {
int i; char str[20],ch[10];
printf(“\n Enter a string”); int l1,l2,i,j,c;
gets(str); printf("\n Enter a string");
printf(“\n Enter a character:”); gets(str);
ch=getche(); printf("\n Enter sub-string:");
for(i=0;str[i]!=’\0’;i++); gets(ch);
{ for(l1=0;str[l1]!='\0';l1++);
if(ch==str[i]) for(l2=0;ch[l2]!='\0';l2++);
{ for(i=0;i<l1;)
printf(“%c found at position %d”,ch,(i+1)); {
exit(0); j=c=0;
} while(ch[j]==str[i] && str[i]!='\0')
} {
printf(“\n Character Not found”); c++;
} i++;
j++;
}
if(c==l2)
{
printf("%s found in %s at %d position",ch,str, i-
l2+1);
exit(1);
}
else i++;
}
printf("Sub-string not found");
}
/* Program to find the total occurrence of a /* Program to find the occurrence of a sub-
character in a given String */ string in a given String */
main() #include<stdlib.h>
{ main()
char str[20],ch; {
int i,c=0; char str[20],ch[10];
printf(“\n Enter a string”); int l1,l2,i,j,c1,c2;
gets(str); printf("\n Enter a string");
printf(“\n Enter a character:”); gets(str);
ch=getche(); printf("\n Enter sub-string:");
for(i=0;str[i]!=’\0’;i++); gets(ch);
{ for(l1=0;str[l1]!='\0';l1++);
if(ch==str[i]) for(l2=0;ch[l2]!='\0';l2++);
c++; for(i=0;i<l1;)
} {
printf(“\n No. of times %c found in %s : %d”, ch, j=c1=0;
str, c); while(ch[j]==str[i] && str[i]!='\0')
} {
c1++;
i++;
j++;
}
if(c1==l2)
{
c2++;
c1=0;
}
else i++;
}
printf(“\n No. of times %s found in %s : %d”, ch,
str, c2);

Multi-Dimensional Arrays
A multi-dimensional array is an array of single dimensional arrays. Multi-dimensional arrays make it
easier to represent multi-dimensional objects such as graphs, matrices etc,. Each element is identified
with its row and column values.

Syntax:: datatype array_name[exp1][exp2]...[expn];

Eg: 2-D integer array


int a[3[4]; a[0][0] a[0][1] a[0][2] a[0][3]
I element a[0][0] 2 3 4 5
II element a[0][1] a[1][0] a[1][1] a[1][2] a[1][3]
... 6 7 8 9
a[2][0] a[2][1] a[2][2] a[2][3]
Initilization
2 3 5 7
int a[3][4] = { 2,3,4,5,6,7,8,9,2,3,5,7};
= {{2,3,4,5},{6,7,8,9},{2,3,5,7}};

/* Program to read a matrix of order 3 x 4 and /* Program to read a matrix of order m x n


display */ and display */
main() main()
{ {
int a[3][4],i,j; int a[10][10],i,j,m,n;
printf(“\n Enter Matrix:”); printf(“\n Enter the order of the matrix:”);
for(i=0;i<3;i++) scanf(“%d%d”,&m,&n);
for(j=0;j<4;j++) printf(“\n Enter Matrix:”);
{ for(i=0;i<m;i++)
printf(“\n Enter a number:”); for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]); {
} printf(“\n Enter a number:”);
printf(“\n Entered Matrix is”); scanf(“%d”,&a[i][j]);
for(i=0;i<3;i++) }
{ printf(“\n Entered Matrix is”);
for(j=0;j<4;j++) for(i=0;i<m;i++)
printf(“%5d”,a[i][j]); {
printf(“\n”); for(j=0;j<n;j++)
} printf(“%5d”,a[i][j]);
printf(“\n”);
}
/* Program to find the transpose of a matrix */ /* Program to find the sum of two matrices */
main() main()
{ {
int a[10][10],b[10][10],i,j,m,n; int a[3][4],b[3][4],c[3][4],i,j;
printf(“\n Enter the order of the matrix:”); printf(“\n Enter I Matrix:”);
scanf(“%d%d”,&m,&n); for(i=0;i<3;i++)
printf(“\n Enter Matrix:”); for(j=0;j<4;j++)
for(i=0;i<m;i++) {
for(j=0;j<n;j++) printf(“\n Enter a number:”);
{ scanf(“%d”,&a[i][j]);
printf(“\n Enter a number:”); }
scanf(“%d”,&a[i][j]);
} printf(“\n Enter II Matrix:”);
printf(“\n Entered Matrix is”); for(i=0;i<3;i++)
for(i=0;i<m;i++) for(j=0;j<4;j++)
{ {
for(j=0;j<n;j++) printf(“\n Enter a number:”);
printf(“%5d”,a[i][j]); scanf(“%d”,&b[i][j]);
printf(“\n”); }
}
for(i=0;i<m;i++) for(i=0;i<3;i++)
for(j=0;j<n;j++) for(j=0;j<4;j++)
b[j][i]=a[i][j]; c[i][j]=a[i][j]+b[i][j];
printf(“\nTransposed Matrix is”);
for(i=0;i<n;i++) printf(“\nResultant Sum of Matrices”);
{ for(i=0;i<3;i++)
for(j=0;j<m;j++) {
printf(“%5d”,a[i][j]); for(j=0;j<4;j++)
printf(“\n”); printf(“%5d”,c[i][j]);
} printf(“\n”);
} }

/*Program to perform matrix multiplication of /*Program to perform matrix multiplication of


3x3 order */ given order */
main()
main() {
{ int a[10][10],b[10][10],c[10][10],m,n,p,q,i,j,k;
int a[3][3],b[3][3],c[3][3],i,j,k;
printf(“Enter the order of I matrix:”);
printf(“\n Enter I Matrix:”); scanf(“%d%d”,&m,&n);
for(i=0;i<3;i++)
for(j=0;j<3;j++) printf(“Enter the order of II matrix:”);
{ scanf(“%d%d”,&p,&q);
printf(“\n Enter a number:”);
scanf(“%d”,&a[i][j]); if(n!=p)
} printf(“\nMatrix multiplication not possible”);

printf(“\n Enter II Matrix:”); else


for(i=0;i<3;i++) {
for(j=0;j<3;j++) printf(“\n Enter I Matrix:”);
{ for(i=0;i<m;i++)
printf(“\n Enter a number:”); for(j=0;j<n;j++)
scanf(“%d”,&b[i][j]); {
} printf(“\n Enter a number:”);
scanf(“%d”,&a[i][j]);
for(i=0;i<3;i++) }
for(j=0;j<3;j++)
{ printf(“\n Enter II Matrix:”);
c[i][j]=0; for(i=0;i<p;i++)
for(k=0;k<3;k++) for(j=0;j<q;j++)
c[i][j]=c[i][j]+a[i][k]*b[k][j]; {
} printf(“\n Enter a number:”);
scanf(“%d”,&b[i][j]);
printf(“\nResultant Product of Matrices”); }
for(i=0;i<3;i++)
{ for(i=0;i<m;i++)
for(j=0;j<3;j++) for(j=0;j<q;j++)
printf(“%5d”,c[i][j]); {
printf(“\n”); c[i][j]=0;
} for(k=0;k<p;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}

printf(“\nResultant Product of Matrices”);


for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf(“%5d”,c[i][j]);
printf(“\n”);
}
}

Passing Array as an argument to a function 2-D Character Arrays


To pass arrays as an argument to a function, only When we declare 2-D character array, the first
the name of the array without subscript has to be expression specifies no. of strings and the second
specified in the function call and an array has to expression specifies the size of each string.
be declared in the function definition. char strs[5][20];
/*Program */
int i; /*Program */
main() main()
{ {
int a[10]; char strs[5][30];
for(i=0;i<10;i++) int i;
{ for(i=0;i<5;i++)
printf(“\n Enter No.’); {
scanf(“%d”,&a[i][j]); printf(“Enter String:’);
} gets(str[i]);
display(a); /*display(a,10)*/ }
} for(i=0;i<5;i++)
display(int ary[10]) /*display(int a[],int n) */ printf(“\n%s”,str[i]);
/*display(int ary[]) */ }
/*display(int *ary) */
{
for(i=0;i<10;i++)
printf(“%3d”,ary[i]);
}
Storage Classes
When we define or declare a variable in C, a characteristic called storage class is associated with each
variable. The variable defines the life span of the variable and its availability or scope.
 The life span of a variable specifies the duration for which the variable will retain the value.
 The scope of the variable indicates the parts of the program where the variable is used.
There are four types of storage classes
 auto[matic]
 static
 register
 extern[al]

‘auto’[matic] storage class


Variables belonging to automatic storage class are called local variables.
Syntax: auto datatype <variable_name>;
Variables declared as local variables can be accessed only in the function in which they are declared.
The life time of the variable is limited only until the function is active. Once the control comes out of
the function, the value in the variable is lost.
/*Program */ num()
main() {
{ auto int j=10;
auto int i; /* int j; j is a local variable defined for
/* int i; i is a local variable accessed only each function call and is accessed only in the
in the main() */ num() */
for(i=1;i<=10;i++) printf(“%3d”,j);
num(); j++;
} }
Output: 10 10 10 10 10 10 10 10 10 10
‘static’ storage class
Static variables are the variables that are available in a function in which they are defined. They do not
lose their value when the function is terminated. These types of variables are present throughout the
program but are only accessible in the function in which they are originally defined.
Syntax: static datatype <variable_name>;
/*Program */ num()
main() {
{ static int j=10;
int i; /* j is a static variable defined only once and is
for(i=1;i<=10;i++) accessed only in the num(). It retains the value
num(); within function calls */
} printf(“%3d”,j);
j++;
}
Output: 10 11 12 13 14 15 16 17 18 19

‘register’ storage class


In a computer, the variables are either stored in memory or in registers. Variables to be stored in
registers are declared using keyword ‘register’ before variable declaration.
Syntax: register type <variable_name>;
When a variable is declared as register variable, instead of allocating the space in the main memory,
one of the CPU registers, if available, is used to store the value. If all the CPU registers are already in
use, the compiler allocates space in the main memory even though it is declared using register storage
class.
main()
{
register int i;
for(i=0;i<1000;i++)
printf(“%d”,i);
}

‘extern’[al] storage class


Variables that belong to extern[al] storage class are available through out the program. These variables
are also known as global variables. ‘extern’ keyword is used before variable declaration to declare an
external variable.
Syntax: extern type variable_name
A global variable defined in one program can be used in another program by re-declaring the variable
using external storage class in second program.
/* Save the program with the name ‘calc.c’ */ /* Save the program as ‘arth.c’ */
#include “arth.c” extern int result;
int result; /* variable ‘result’ will point to same memory
main() location defined in calc.c as it is declared using
{ extern storage class */
int a,b; sum(int p,int q)
printf(“\n Enter two numbers:”); {
scanf(“%d%d”,&a,&b); result=p+q;
sum(a,b); }
printf(“Sum: %d”,result);
diff(a,b); diff(int a,int b)
printf(“Difference : %d”,result); {
} result=a-b;
}

Recursion
Recursion is the process of defining something in terms of itself. A function is said to recursive if a
statement in the body of the function calls itself.
Recursive functions can be effectively used to solve problems where the solution is expressed in terms
of successively applying the same solution to the subsets of the problem.
Eg.
main()
{
fun();
}
func()
{
printf(“\n Recursive Function”);
fun();
}

In the above program, the function will never terminate because a condition is not mentioned so as to go
back to the calling function. Therefore, when we write recursive functions, we must have an ‘if’
statement somewhere in the body of the function to force the function to return to the calling function
without executing the recursive calls again at some point of time.

Factorial of a number /* Factorial of a number using recursion */


0! = 1 fcat(0) = 1 main()
1! = 1 fact(1) = 1 {
2! = 2 * 1! fact(2) = 2 * fact(1) int n;
3! = 3 * 2! fact(3) = 3 * fact(2)
n! = n * (n-1)! fact(n) = n * fact(n-1) printf(“Enter a number:”);
/*Factorial of a number using without recursion */ scanf(%d”,&n);
main()
{ printf(“Factorial of %d is %d”, n,fact(n));
int n; }
printf(“Enter a number:”);
scanf(%d”,&n); fact(int n)
printf(“Factorial of %d is %d”, n,fact(n)); {
} if(n==0 || n==1)
fact(int n) return(1);
{
int i,f=1; else
for(i=1;i<=n;i++) return(n*fact(n-1);
f=f*i; }
retrun(f);
}

Fibonacci series
1 1 2 3 5 8 13 21 ...
fibo(1) = fact(2) = 1
fact(3) = fibo(2) + fibo(1)
fact(4) = fibo(3) + fibo(2)
fact(n) = fibo(n-1) + fact(n-2)
/*Printing nth Fibonacci number using /*Printing first n Fibonacci numbers using
recursion*/ recursion*/
main() main()
{ {
int n; int n,i;
printf(“Enter a number:”); printf(“Enter a number:”);
scanf(%d”,&n); scanf(%d”,&n);
printf(“% d fibinacci number is %d”, n,fibo(n)); for(i=1;i<=n;i++)
} printf(“% d fibinacci number is %d”, n,fibo(i));
fibo(int n) }
{ fibo(int n)
if(n==1 || n==2) {
return(1); if(n==1 || n==2)
else return(1);
return(fibo(n-1) + fact(n-2)); else
} return(fibo(n-1) + fact(n-2));
}

Pointers
A pointer is a variable that holds the memory address of another variable. Pointers provide a way to
access a variable without referring to the variable directly.
Syntax: datatype *ptr_var_name;
Eg: int i,*p
p= &i; &-> specifies address of i.
Note: *p indicates value stored at the address in p.

main() Output
{
int i=10,*p;
p=&i;
printf(“\nAddress of i;%u”,&i); /* Address of i */
printf(“\nAddress of i using p;%u”,p); /* Address of i */
printf(“\nAddress of p;%u”,&p); /* Address of p */
printf(“\nValue in i;%d”,i); /* value in i =10*/
printf(“\nValue in i using p:%d”,*p); /* value in i using p=10*/
printf(“\nvalue in p;%u”,p); /* value in p = address of i*/
}
Applications of pointers
 Pointers are used to return more than onle value from a function.
 Pointers are used to pass arrays and strings from one function to another.
 Pointers are used to allocate memory and access it.
 Pointers are used to create complex data structures.

Note 1: A ‘NULL’ value can be assigned to a pointer either through a figurative constant or ‘0’.
int *p= NULL; or int *p=0;

Note 2: The declaration of int *p means p can hold the address of an integer variable only.

/*Program to add two numbers */


main()
{
int i,j,*p,*q;
p=&i;
q=&j;
printf(“\n Enter two numbers:”);
scanf(“%d%d”,p,q); /* scanf(“%d%d”,&i,&j); */
printf(“Sum = %d”,*p+*q); /* printf(“Sum = %d”,i+j); */
}

Call by Value Call by Reference


In C language, by default, all the values are When we pass the memory address of a variable
passed to a function are by value. The process of as an argument to the called function, the
passing the values in variables using actual phenomenon is known as Call By Reference.
arguments is known as Call By Value. In call by reference, C allows the called function
Call by value passes the values of the actual to access the actual memory location of the passed
argument to the temporary formal variables. A arguments and therefore the called function can
called function cannot access the actual memory change the value of the arguments passed.
location of passed argument and therefore cannot
change the contents of the actual variable.
main() main()
{ {
int a,b; int a,b;
printf(“\n Enter two numbers:”); printf(“\n Enter two numbers:”);
scanf(“%d%d”,&a,&b); scanf(“%d%d”,&a,&b);
printf(“\nBefore Passing a=%d b=%d”,a,b); printf(“\nBefore Passing a=%d b=%d”,a,b);
change(a,b); /* call by value */ change(&a,&b); /* call by reference */
printf(“\nAfter Passing a=%d b=%d”,a,b); printf(“\nAfter Passing a=%d b=%d”,a,b);
} }
change(int p,int q) change(int *p,int *q)
{ {
int temp; int temp;
temp=p; temp=*p;
p=q; *p=*q;
q=temp; *q=temp;
} }
Output: Output:
Enter two numbers: 10 20 Enter two numbers: 10 20
Before Passing a=10 b=20 Before Passing a=10 b=20
After Passing a=10 b=20 After Passing a=20 b=10

Pointer Arithmetic
Addition and subtraction are the only operations which can be performed on pointers.
Eg: int i=10,*p; address of i=1023(say). Integer occupies two bytes of memory i.e, 1023 & 1024.
p=&i; p contains 1023.
p=p+1; p points to next integer location i.e, 1025
p=p-1 p points to previous integer location i.e, 1023
To increment the value i i++ or (*p)++ ++i or ++*p i=i+1 or *p=*p+1

Comparison of pointers
We can compare two addresses stored in two pointers.
Eg: Assume p and q are two pointers storing the address of two integer locations
p<q => p has the address which comes before in memory than the address in q
p>q => p has the address which comes after in memory than the address in q
p==q => p and q points to same location in memory. i.e, they posses same address
Pointers and Single Dimension Array
In a single dimension array, an array name is actually a pointer to the first element in that array
Eg: int a[10];
Element Address Value
st
1 &a[0] or a a[0] or *a
2nd &a[1] or a+1 a[1] or *(a+1)
rd
3 &a[2] or a+2 a[2] or *(a+2)
...
th
n &a[n-1] or a+(n-1) a[n-1] or *(a+(n-1))
Address of an element can be expressed in two ways
 By writing the actual array element preceded by &
 Writing an expression in which the array subscript is added to the array name.
Eg: main()
{
int a[10] = {2,4,6,8,1,3,5,7,9,0}, i;
for(i=0;i<10;i++)
{
printf(“\n Address: &a[%d] = %u a+%d = %u”, i,&a[i],i,a+i);
printf(“\n Value: a[%d] = %d *(a+%d) = %d”, i,a[i],i,*(a+i));
}
Note: when you pas an array as an argument to a function, only the name of the array is mentioned in the
function call. As the array name itself contains the address of the first location, a new array is not created
in the function definition. In fact, it points to the same array which has been created in calling function.
Eg: int i;
main() Output
{
int a[10] = {2,4,6,8,1,3,5,7,9,0};
display(a);
for(i=0;i<10;i++)
printf(“%4d”, a[i]); 3 5 7 9 2 4 6 8 10 1
}
display(int *ary)
{
for(i=0;i<10;i++)
{
printf(“%4d”, ary[i]); 2468135790
ary[i]++;
}

Note: ary+1 doesn’t move the ary to (ary+1)th position, it just points to that position. Whereas, ary++
actually tries to move ary by one one position.

Pointers and Multi-Dimensional Arrays


A multi-dimensional array can be represented with an equivalent pointer notation. This is so because a
multi dimensional array is actually a collection of single dimensional array.
Syntax: type (*array_name)[<exp 2>][<exp 3>]...[<exp n>]; instead of
type array_name)[<exp1>][<exp 2>][<exp 3>]...[<exp n>];
Eg: int (*a)[4]; instead of int a[3][4];
rd nd
To get 3 row 2 element, we write
a[2][1] or *( *(a+2)+1 );
Address

Note: In the above definition, the array_ pointer must be placed parenthesis else the definition would
represent an array of pointers.

Pointers and String


Strings are nothing but single dimensional character arrays. A single dimensional character array is
horizontally organized and has only one row and multiple columns corresponding to the number of
characters in the string plus an extra column for storing the NULL (‘\0’) character.

String Functions
C compiler comes with standard library header file ‘string.h’ which provides several functions to
manipulate strings.
Function Description
strlen(str) Returns the length of the string str
strcat(s1,s2) Concatenates string s2 at the end of s1
strcpy(s1,s2) Copies the string s2 at the end of s1
strcmp(s,s2) Compares two strings and returns
a) 0 if s1==s2 b) <0 if s1<s2 c) >0 if s1>s2
strchr(s,ch) Returns the address of the first occurrence of character ch in string s
strstr(str1,str2) Returns the address of the first occurrence of string str2 in string str1
strrev(s) Reverses a given string

/* Program to find the length of the string */ /* Program to reverse a string */


#include<string.h> #include<string.h>
main() main()
{ {
char str[20]; char str[20];
int l; printf(“\n Enter a string:”);
printf(“\n Enter a string:”); gets(str);
gets(str); printf(“\nBefore Reversing:%s”,str);
l=strlen(str); strrev(str);
printf(“Length of the %s : %d”,str,l); printf(“\nAfter Reversing: %s”,str);
} }
/* Program to concatenate two strings */ /* Program to copy one string into another */
#include<string.h> #include<string.h>
main() main()
{ {
char s1[40],s2[20]; char s1[40],s2[20];
printf(“\n Enter string 1:”); printf(“\n Enter string 1:”);
gets(s1); gets(s1);
printf(“\n Enter string 2:”); printf(“Entered string s1 :%s”,s1);
gets(s2); strcpy(s2,s1);
printf(“Before Concatenation :%s \t %s”,s1,s2); printf(“Copied string :%s”,s2);
strcat(s1,s2); }
printf(“After Concatenation :%s \t %s”,s1,s2);
}
/* Program to compare two strings */ /*Program to find the first occurrence of a given
#include<string.h> character in a given string */
main() main()
{ {
char s1[40],s2[20]; char str[20],ch,*p;
int c;
printf(“\n Enter string 1:”); printf(“\n Enter a string:”);
gets(s1); gets(str);
printf(“\n Enter string 2:”);
gets(s2); printf(“Enter a character:”);
printf(“Entered Strings :%s \t %s”,s1,s2); ch=getche();
c = strcmp(s1,s2);
if(c==0) p=strchr(str,ch);
printf(“\nBoth strings are equal”); if(p==NULL)
else if(c<0) printf(“\nGiven character is not found”);
printf(“\n s1 is less than s2”); else
else printf(“ %c found in %s at %d position”,
printf(“\n s1 is greater than s2”); ch,str, p-str+1);
} }
/*Program to count the occurrence of a given /*Program to find the first occurrence of a given
substring in a given string */ substring in a given string */
main() main()
{ {
char str[20], ch[10],*p; char str[20],ch[10],*p;
int count; printf(“\n Enter a string:”);
printf(“\n Enter a string:”); gets(str);
gets(str); printf(“Enter a substring:”);
printf(“Enter sub string:”); gets(ch);
gets(ch); p=strstr(str,ch);
p=strstr(str,ch); if(p==NULL)
while(p!=NULL) printf(“\n string not found”);
{ else
count++; printf(“ %s found in %s at %d position”,
s=p+strlen(ch); ch,str, p-str+1);
p=strstr(str,ch); }
}
printf(“\n Count = %d”, count);
}

Dynamic Memory Allocation


The allocation of memory as when required in program is known as Dynamic Memory Allocation. In this
concept, the allocation of memory is done during the execution of the program. C library contains a
header file “alloc.h” that contains functions that are used for allocation and de-allocation of memory
during program execution. Memory management functions in C are malloc(), calloc(), realloc() and
free().

malloc() free() calloc() realloc()


This function is used to C provides a free() This function is usually This function is used to
allocate requested which is used to release used to allocate memory reallocate the memory.
number of bytes from the used memory, when at run time for storing The allocated memory
the free pool of no longer needed. derived data types such can be increased or
memory, and returns a Syntax: as arrays and structures. decreased.
pointer to a block of free(<pointer>); calloc() allocates Syntax: type
contiguous memory of multiple blocks of *pointer_variable =
the specified size. storage, each block realloc (<pointer>,
Syntax: type being of same size, and <new Memory size>);
*pointer_variable = then set all bytes of the
(<cast type>*) memory in the block to
malloc(number of bytes zero.
required); Syntax: type
This function allocates a *pointer_variable =
block of memory and (<cast type>*) calloc
returns a pointer which (number of blocks, size
points to the first byte of of each block);
the allocated space or
memory block. If the
allocation is not
successful, it returns a
NULL pointer.
Note: malloc() allocates
a void memory which
has to be type-casted.
Difference between malloc() and calloc()
malloc() calloc()
Allocates a single contiguous block of memory Allocates a number of blocks of memory in
contiguous form
Default memory allocation contains undefined Default memory allocation is initialized to zero
values
Needs only one argument to allocate memory Needs two arguments to allocate memory
Generally used to allocate memory for basic data Generally used to allocate memory for derived data
types at run-time types at run-time

/*Program to allocate memory for single /* Program to allocate memory for 2-D array */
element*/ #include<alloc.h>
#include<alloc.h> main()
main() {
{ int (*p)[4],i,j;
int *p; p=(int*)malloc(3 * 4 *sizeof(int));
p=(int*)malloc(sizeof(int)); /* p=(int*)calloc(3 * 4, sizeof(int)); */
/* p=(int*)calloc(sizeof(int)); */ for(i=0;i<3;i++)
printf(“\n Enter a Number:”); for(j=0;j<4;j++)
scanf(%d”,p); {
printf(“Entered number: %d”, *p); printf(“\n Enter a Number:”);
} scanf(%d”,&p[i][j]);/*printf(“ %d”,*(p+i)+j);*/
/* Program to allocate memory for Single }
Dimension Array */ for(i=0;i<3;i++)
#include<alloc.h> {
main() for(j=0;j<4;j++)
{ printf(“ %5d”,p[i]); /*printf(“ %5d”,*(*(p+i)+j));*/
int *p,i; printf(“\n”);
p=(int*)malloc(10 * sizeof(int)); }
/* p=(int*)calloc(10, sizeof(int)); */ }
for(i=0;i<10;i++)
{
printf(“\n Enter a Number:”);
scanf(%d”,&p[i]);
}
for(i=0;i<10;i++)
printf(“ %5d”,p[i]);
}

Array of pointers
It is possible to create array of pointers which are used to store addresses.
main()
{
int a[5] = {10,20,30,40,50}
int *p[5],i; /* array p can store 5 addresses */
for(i=0;i<5;i++)
{
p[i]=&a[i];
printf(“%5d”,*p[i]);
}
Multi Dimension Array of Pointers
A multi-dimension array can be expressed in terms of array of pointers.
Syntax: type *array_name[<exp 1>][<exp 2>]...[<exp n-1>]; instead of
type array_name)[<exp1>][<exp 2>][<exp 3>]...[<exp n>];
The last expression is omitted when defining an array of pointers whereas the first expression is omitted
when defining a pointer to a group of arrays.
Eg: int a[5][6] can be expressed as int *a[5];
3rd row 4th column element can be obtained as
a[2][3] or *( a[2]+3 )
address

Pointers and Array of Strings


Pointers can be associated with array of strings to enable the users to store variable number of columns
(strings of different length) for different rows.
Character arrays with rows of varying length are called ragged arrays and are better handled using
pointers.
Eg: char *name[4] = { “KAKINADA”, “RAJAMUNDRY”, “VIJAYAWADA”, “VIZAG”};

name[0] K A K I N A D A \0
name[1] R A J A M U N D R Y \0
name[2] V I J A Y A W A D A \0
name[3] V I Z A G \0
Note: When using ragged arrays, we cannot accept values to the array directly using scanf() or gets().
/*Program to create an integer array /*Program to read strings in ragged arrays and
dynamically */ display */
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
#include<alloc.h> #include<alloc.h>
void main() #include<string.h>
{ void main()
int *p[5],i,j,n; {
printf("\n Enter the size of each integer row"); char *str[5],temp[30];
scanf("%d",&n); int i;
for(i=0;i<5;i++) for(i=0;i<5;i++)
{ {
p[i]=(int*)malloc(n *sizeof(int)); printf("\n Enter a Name:");
for(j=0;j<n;j++) gets(temp);
{ str[i]=(char*)malloc((strlen(str)+1)*sizeof(char));
printf("\n Enter a Number:"); strcpy(name[i],temp);
scanf("%d",&p[i][j]); /*printf(“ %d”,p[i]+j);*/ }
} for(i=0;i<5;i++)
} {
for(i=0;i<5;i++) printf("\n%s",name[i]);
{ }
for(j=0;j<n;j++) }
printf("%5d",p[i][j]);
/*printf("%5d",*(p[i]+j));*/
printf("\n");
}
}

Multi dimension pointers


It is possible to have pointer to another pointer
Syntax: type **double_pointer;
Eg: main()
{
int **d_ptr, *ptr, i=10;
ptr=&i;
d_ptr=&ptr;
printf(“Value in i= %d %d %d”,i,*ptr,**d_ptr);
}
Pointer to Function
We can create a pointer to a function. This is an indirection method of referring to a function as pointer
but providing indirection.
Indirect reference to a function in simple terms means calling the function using a function pointer which
is a variable that points to that function.
Syntax: return_type (*function_pointer_name)();

/* Program to store the address of strlen() in a /* Program to store the address of strcmp() in a
function pointer and invoke it */ function pointer and invoke it */
#include<string.h> #include<string.h>
main(); check(char *a,char *b,int (*cmp)());
{ main();
char str[30]; {
int l,(*len)(); char str1[30],str2[30];
len=strlen; int (*c)();
printf(“\n Enter a String:”); c=strcmp;
gets(str); printf(“\n Enter two Strings:”);
l=(*len)(str); /* l=strlen(str) */ gets(str1);
printf(“length of %s is %d”,str,l); gets(str2);
} check(str1,str2,c);
}
check(char *a,char *b,int (*cmp)())
{
int n;
n=(*cmp)(a,b); /* n = strcmp(a,b); */
if(n==0)
printf(“\n Strings are equal”);
esle
printf(“\nStrings are not equal”);
}

Structures, Unions and Enumeration


C allows custom data types to be created in various ways.

Structure
A structure is grouping of variables under one name. A Structure consists of number of data items, which
need not be of same type, grouped together.
A Structure is a powerful tool in the hands of programmer which can be used to handle a group of
logically related data items.
Defining a Structure
A structure definition forms a template that is used to carry structure variables. The variables that make
up a structure are called structure elements or structure members. ‘struct’ keyboard is used to define a
structure.
Syntax: struct structure_name
{
structure members;
} structure variables;
Eg:
struct employ struct student struct phone
{ { {
int empno; int rno; int rno;
char name[30], dept[20]; char name[30]; char name[30];
char design[20]; float fee; long int phno;
float sal; }; };
};

Creating structure variables


Syntax:: struct structure_name variable_name;
Eg: struct employ e;
struct phone p,r;
struct student s;
To assign values
struct phone p={123,”Sekhar”, 9848223667};
To access individual members of a structure: dot(.) operator is used to access structure members.
Syntax: structure_variable.structure_member;
eg: p.rno, p.name,p.phno;
/* program to read values into a structure and display them */
struct employ
{
int empno;
char name[30],design[20],dept[20];
float sal;
};
main()
{
struct employ e;
printf(“\n Enter employ number:”);
scanf(“%d”,&e.empno);
fflush(stdin);
printf(“\n Enter name, designattion, department”)
gets(e.name);
gets(e.desig);
gets(e.dept);
printf(“\n Enter Salary:”);
scanf(“%f”,&e.sal);
printf(“\n\nEmploy No.:%d Name: %s Designation:%s Department:%s Salary:%f ”,e.empno,e.name,
e.desig, e.dept, e.sal);
}
Array of Structures
It is possible to create array of structure variables. To create an array, a structure is first defined and then,
an array of variables of structure type is defined.
Eg: struct phone p[3];

Assigning values
struct phone p[3]={ {1,”sekhar”, 2306314}, {2,”ravi”,2306315} , {3,”arun”,2306312}};

/* Program to read values in a structure array and display */


main()
{
struct phone
{
int rno;
char name[30];
long int ph;
};
struct phone p[5];
int i;
for(i=0;i<5;i++)
{
printf(“\n Enter Number:”);
scanf(“%d”, &p[i].rno);
fflush(stdin);
printf(“\n Enter Name:”);
gets(p[i].name);
printf(“\n Enter Phone Number:”);
scanf(“%ld”,&p[i].ph);
}
for(i=0;i<5;i++)
printf(“\nNo.:%d Name:%s Phone No: %ld”,p[i].no,p[i].name,p[i].ph);
}

Structures within a structure


C permits nesting of structures which means we can declare a structure within a structure.

Eg: struct student


{
int rno;
char name[30];
};

struct subject
{
struct student s;
char sub[30];
int marks;
};

To assign values to members:


struct subject p={ {1,”Ajay”},”computers”,80 };

To access members of structure


struct subject ss;
ss.s.rno ss.s.name
ss.sub ss.marks
/* Program to demonstrate structure within a structure */
main()
{
struct student
{
int rno;
char name[30];
};
struct subject
{
struct student s;
char sub[30];
int marks;
}ss;
printf(“\n Enter rno:”);
scanf((“%d”, &ss.s.rno);
fflush(stdin);
printf(“\n Enter Name:”);
gets(ss.s.name);
printf(“\n Enter Subject:”);
gets(ss.sub);
printf(“\n Enter Marks”);
scanf(“%d”, &ss.marks);
printf(“\n Number: %d Name:%s Subject: %s Marks %d”,ss.s.rno,ss.s.name,s.sub,s.marks);
}
/* Program to pass structure as an argument to a function */
main()
{
struct phone
{
int rno;
char name[30];
long int ph;
};
struct phone p;
printf(“\n Enter Number:”);
scanf(“%d”, &p.rno);
fflush(stdin);
printf(“\n Enter Name:”);
gets(p.name);
printf(“\n Enter Phone Number:”);
scanf(“%ld”,&p.ph);
display(p);
}
display(struct {int no,char n[30],long in phno}x)
/*structure is re-defined in the function definition as the structure phone is local to main */
{
printf(“\nNo.:%d Name:%s Phone No: %ld”,x.no,x.n,x.phno);
}
Pointer to structures
We can create structure pointers which are used to generate call by reference as well as linked-list data
structure.
Syntax:: struct structure_name *structure_pointer;
Eg: struct phone
{
int rno;
char name[30];
long int phno;
};
struct phone s,*p;
p=&s;
To access structure members
‘->’ operator is used to access elements of a structure using pointer.
Eg: p->rno or (*p).rno p->name or (*p).name
p->phno or (*p).phno

/*Program to read data using structure /*Program to allocate memory for a structure */
pointer*/ #include<alloc.h>
main() struct phone
{ {
struct phone int rno;
{ char name[30];
int rno; long int ph;
char name[30]; };
long int ph; main()
}; {
struct phone s,*p; struct phone *p;
p=&s; p=(struct phone*)malloc(sizeof(struct phone));
printf(“\n Enter Number:”); printf(“\n Enter Number:”);
scanf(“%d”, &p->rno); scanf(“%d”, &p->rno);
fflush(stdin); fflush(stdin);
printf(“\nEnNter Name:”0; printf(“\n Enter Name:”);
gets(p->name); gets(p->name);
printf(“\n Enter Phone Number:”); printf(“\n Enter Phone Number:”);
scanf(“%ld”,&p->ph); scanf(“%ld”,&p->ph);
printf(“\nNo.:%d Name:%s Phone No: %ld”, display(p);
p->.rno,p->name,p->.phno); }
} display(struct phone *x)
{
printf(“\nNo.:%d Name:%s Phone No: %ld”,x-
>rno,x->name,x->ph);
}
Union
Union is a grouping of variables under one name. In union, memory is shared by two or more variables
of different types at different times.
Union follows the same syntax as structure, except that the keyword ‘union’ is used in place of ‘sturct’.
Syntax:: union union_name
{
union members;
}union_variables;
Eg: union temp
{
int i;
float j;
}
The major fundamental difference between structure and union is that in a structure, each member has a
storage location once it is associated with a structure. But in union, all the members use the same
location. It implies that even though a union can contain members of different type, it can handle only
one member at a time.
In case of structure, the storage location allocated is equal to the sum of the storage capacity of individual
members. In case of union, the storage size is equal to the size of the largest member of the union.

/* program to demonstrate union */


main()
{
union abc
{
int a;
char ch[2];
}
};
union abc x;
x.a=1354;
printf(“x.a=%d”,x.a);
printf(“x.ch[0]=%c”,x.ch[0]);
printf(“x.ch[1]=%c”,x.ch[1]);
x.ch[0]=’a’;
x.ch[1]=’b’;
printf(“x.a=%d”,x.a);
printf(“x.ch[0]=%c”,x.ch[0]);
printf(“x.ch[1]=%c”,x.ch[1]);
}

Note: As we can include a structure within a structure, a union can be included in a union. There can be a
structure in union and a union in structure.

/*program to demonstrate structure within a union */


main()
{
struct abc
{
int i;
char s[2];
};
struct xyz
{
int j;
char t[2];
};
union abc_xyz
{
struct abc m;
struct xyz n;
};
union abc_xyz p;
p.m.i=10;
p.n.t[0]=’U’;
p.n.t[1]=’V’;
printf(“\n i=%d”,p.m.i);
printf(“\n s[0]=%c”,p.m.s[0]);
printf(“\n s[1]=%c”,p.m.s[1]);
printf(“\n j=%d”,p.n.j);
printf(“\n t[0]=%c”,p.n.t[0]);
printf(“\n t[1]=%c”,p.n.t[1]);
}

Enumeration
It is used to invent your own data type and define what values the variables of this data type can take.
Syntax:: enum enumeration_tag
{
Enumeration members;
}enumeration variables;
Eg: enum cities
{ Kakinada, Vizag, Vijayawada, Guntur };
Note: By default, the members are internally stored as integer constants starting from ‘0’.
Kakinada-0 Vizag-1
Vijayawada-2 Guntur-3
Note: we can change the default values of enumeration elements.
Eg: enum cities
{
Kakinada=0,Vizag=4,
Vijayawada=8,Guntur };
Program:
enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
main()
{
Enum week today;
today=Wednesday;
printf(“%d day”,today+1);
}

Files
File Input and Output
All I/O operations are carried out using functions from the standard C library. I/O is unique because data
may be transferred in its internal binary representation or in a human readable text format making it easy
to create files to fit for any need.
Stream: The I/O system in C provides an interface to the user. This interface is independent of actual
device being accessed. This interface is not actually a file but an abstract representation of the device,
called as stream and, the actual device is called the ‘File’.
There are two types of streams- Text stream and Binary stream.
Text Stream
It is a sequence of characters which can be organized into lines terminated by a new line character.
Binary Stream
It is sequence of bytes with one to one correspondence to those in external devices.
File
A file can be anything from a device file to a terminal or a printer. A file can associated with a stream by
performing an open operation. And likewise, it can be de-associated with the stream by a close operation.
Basic File Functions
Function Description Function Description
fopen() Opens a file fclose() Closes a file
fputc() Writes a character to a file fgetc() Reads a character from a file
fputs() Writes a string to a file fgets() Reads a string from a file
fprintf() Writes data to a file. It is to a file what printf() is fscanf() Reads data from a file. It is to
to console a file what scanf() is to
console
fwrite() Writes a complete block of data to a file. fread() Reads a complete block of
data from a file
rewind() Moves the file locator to the first byte in the file. fseek() Seeks to the specified byte in a
(Resets the file position locator to the beginning file.
of the file)
ftell() Tells the current position of the file pointer in feof() Returns true if end-of-file(eof)
terms of bytes from the beginning. is reached
ferror() Returns true, if an error occurs. fflush() Flushes the stream
remove() Erases the file

File Pointer
A file pointer is pointer to a structure which contains information about the file including its name,
current position of the file position locator, size, whether the file is opened for reading or writing etc.,
Syntax:: FILE *file_pointer;
Eg: FILE *fp;
fopen()
fopen() fopen function opens the stream for use and links a file with that stream. A file pointer is
associated with that file is then returned by fopen().
Syntax: FILE *fopen(const char *name, const char *mode);
‘mode’ specifies the purpose for which the file is being opened.
Mode Description Mode Description
R Opens text file for reading rb Opens binary file for reading
W Creates text file for writing wb Creates binary file for writing
A Appends to a text file ab Appends to a binary file
r+ Opens text file for read/write r+b Opens binary file for read/write
w+ Creates text file for read/write w+b Creates binary file for read/write
a+f Appends or create text file for read/Write a+b Appends or create binary file for read/Write
Steps performed while opening the file
Step 1: Search for the file
Step 2: If found, the file is loaded into memory. If not found, a NULL value is returned.
Step 3: fopen() then sets up a character pointer. It is a part of the file structure and points to the first
character in the file memory while the file is being loaded.
Eg: FILE *fp;
fp=fopen(“name.txt”,”r”);
if(fp=NULL)
{
printf(“File not found”);
exit(1);
}
fclose()
fclose() is used to close a file
Syntax: fclose(FILE *fp);
Note: fcloseall() is used to close all the files which are opened currently. It returns an integer which
specifies the number of strmes that are currently opened. It returns ‘EOF” when an error occurs.
fputc()
fputc() is used to write a character to a file.
Syntax: fputc(int ch, FILE *fp);
fgetc()
fgetc() is used to read a character from a file
Syntax: fgetc(FILE *fp);
/*Program*/
main()
{
FILE *fp;
char ch;
if((fp=fopen(“abc.txt”,”w”) == NULL)
{
printf(“Unable to create the file”);
exit(1);
}
ch=getche();
while(ch!=’*’)
{
fputc(ch,fp);
ch=getche();
}
fclose(fp);
if((fp=fopen(“abc.txt”,”r”) == NULL)
{
printf(“Can’t open the file”);
exit(1);
}
do
{
ch=fgetc(fp);
putchar(ch);
}while(ch!=EOF);
fclose(fp);
}
fputs()
It is used to write strings to a file
Syntax: int fputs(const char *str, FILE *fp);
fgets()
It is used to read strings from a file.
Syntax: chat *fgets(char *str, int length, FILE *fp);
feof()
This function returns a non-zero value if the end-of-file has been reached.
Syntax: int feof(FILE *fp);
ftell()
It returns a long int value which gives the position of the character file pointer from the beginning of the
file in the specified stream.
fseek()
fseek() re-positions the current file pointer by a specified number of bytes from the starting, from the
current position or from the end of the stream depending up on the position specified in fseek().
Syntax: int fseek(FILE *fp, long int offset, int origin);
offset is the number of bytes beyond the file location given in origin. Origin indicates the
beginning position and has three values
SEEK_SET or 0 from the beginning of the file
SEEK_CUR or 1 from the current position of the file
SEEK_END or 2 from the end of the file
main()
{
char str[80];
FILE *fp;
if((fp=fopen(“names.txt”,”w+”)) == NULL)
{
printf(“Can’t create a file”);
exit(1);
}
do
{
printf(“Enter a string. Press enter to exit:”);
gets(str);
strcat(str,”\n”);
fputs(str,fp);
if(ferror(fp))
printf(“Error in writing’);
}while(*str!=’\n’);
rewind(fp);
while(!feof(fp))
{
printf(“The position of the file pointer:%ld”,ftell(fp));
fgets(str,80,fp);
printf(“%s”,str);
}
fclose(fp);
}
Standard streams
When C programs starts execution under DOS, five specified streams are opened automatically by the
operating system. They are
Standard input stream(stdin)
Standard output stream(stdout)
Standard error stream(stderr)
Standard printer stream(stdprn)
Standard auxiliary stream(stdaux)
stdin, stdout,stderr are assigned to systems console. stdprn is assigned to printer port. stdaux is assigned
to first serial port.
fread() and fwrite()
These functions are used to read and write a complete block of data at once to a file respectively.
Syntax: fread(void *buffer, size_t num_bytes, size_t count, FILE *fp);
fwrite(void *buffer, size_t num_bytes, size_t count, FILE *fp);

main() /* program to read/write a structure to a file */


{ main()
int x=10,y; struct student
float p=3.14,q; {
FILE *fp; int rno;
fp=fopen(“Num.txt”,”w+”); char name[20;
fwrite(&x,sizeof(int),1,fp); }*s,*p;
fwrite(&p,sizeof(float),1,fp); FILE *fp;
rewind(fp); s=(struct student *) malloc(sizeof(struct student));
fread(&y,sizeof(int),1,fp); printf(“\n Enter a number:”);
fread(&q,sizeof(float),1,fp); scanf(“%d”,&s->rno);
printf(“y=%d q=%f”,y,q); fflush(stdin);
fclose(fp); printf(“\n Enter name:”);
} gets(s->name);
fp=fopen(“xyz.txt”,”w+”);
fwrite(s,sizeof(struct student),1,fp);
rewind(fp);
p=(struct student*)malloc(sizeof(struct
student),1,fp);
fread(p,sizeof(struct student),1,fp);
printf(“R No.=%d Name=%s”,p->rno,p->name);
fclose(fp);
free(p);
free(s);
}

fprintf() and fscanf()


These functions are used to direct the I/O operations to the file pointed to by the file pointer.
Syntax: fprintf (FILE *fp, “<format specifiers>”, <variable list>);
fscanf (FILE *fp, “<format specifiers>”,<variable list>);
main()
{
FILE *fp;
char name[20];
int no;
fprintf(stdout,”Enter Name and No:”):
fsacnf(stdin, “%s%d”,name,&no);
fp=fopen(“abc.txt”, “w”);
fprintf(fp, “%s%d”name,no);
fclose(fp);
fp=fopen(“abc.txt”, “r”);
fscanf(fp,”%s%d”,name,&no);
fprintf(stdout,”Name=%s Number=%d”,name,no);
fclose(fp);
}
/* Program to copy the contents of one file into another */
main()
{
FILE *s,*d;
char ch;
s=fopen(“temp1.txt”,”w”); /* Create a source file temp1.txt */
ch=getche();
while(ch!=’*”)
{
fputc(ch,s);
ch=getche();
}
fclose(fp);
s=fopen(“temp1.txt”,”r”); /* Open the source file temp1.txt */
d=fopen(“temp2.txt”,”w”); /* Create the target file temp2.txt */
do
{
ch=fgetc(s);
fputc(ch,d);
}while(ch!=EOF);
fcloseall();
d=fopen(“temp2.txt”,”r”); /* Open the target file to read temp1.txt */
do
{
ch=fgetc(d);
putchar(ch);
}while(ch!=EOF);
fclose(d);
}

Searching
It is the process of finding the element in an array until it is found or we reach to the end of the array.
There are two types of searching techniques. They are
a. Linear search b. Binary search
Linear Search
In this technique, we compare each and every element of the array one by one with the element to be
found. The searching stops if the element is found or we reach to the end of the array.

/*Search a number in an array using Linear /*Search a string in an array using Linear
Search*/ Search*/
main() #include<string.h>
{ main()
int a[10],n,i; {
for(i=0;i<10;i++) char a[10][20],n[20];
{ int i;
printf(“\n Enter Number:”); for(i=0;i<10;i++)
scanf(“%d”,&a[i]); {
} printf(“\n Enter a string:”);
printf(“\n Enter the element you want to search”); gets(a[i]);
scanf(“%d”,&n); }
for(i=0;i<10;i++) printf(“\n Enter the string you want to search”);
{ gets(n);
if(a[i]==n) for(i=0;i<10;i++)
{ {
printf(“\nNumber found at position %d”,i+1); if(strcmp(a[i],n)==0)
exit(0); {
} printf(“\nStringr found at position %d”,i+1);
} exit(0);
printf(“\nElement not found”); }
} }
printf(“\nString not found”);
}

Binary Search
This searching technique is applied to sorted array. Here, we compare the middle element of the array
with the element to be found. If found, the searching stops. Otherwise, we check whether the element to
be found is less than or greater than the middle element. If less, the above procedure is applied to the left
half of the array otherwise with the right half. The procedure is continued until the element is found or
we reach to the end of the array.

/* Search a number in a sorted array using /* Search a string in a sorted array using binary
binary search */ search */
main() #include<string.h>
{ main()
int a[10],n,i,l,m,h; {
printf(“\n ENTER NUMBERS IN SORTED char a[10][20],n[20];
ORDER”); int i,l,m,h;
for(i=0;i<10;i++) printf(“\n ENTER ELEMENTS IN SORTED
{ ORDER”);
printf(“\n Enter Number:”); for(i=0;i<10;i++)
scanf(“%d”,&a[i]); {
} printf(“\n Enter a string:”);
printf(“\n Enter the element you want to search”); gets(a[i]);
scanf(“%d”,&n); }
l=0; printf(“\n Enter the string you want to search”);
h=9; gets(n);
while(l<=h) l=0;
{ h=9;
m=(l+h)/2; while(l<=h)
if(a[m]==n) {
{ m=(l+h)/2;
printf(“\nNumber found at position %d”,m+1); if(strcmp(a[m],n==0)
exit(0); {
} printf(“\nString found at position %d”,m+1);
else if(a[m]<n) exit(0);
l=m+1; }
else else if(strcmp(a[m],n)<0)
h=m-1; l=m+1;
} else
printf(“\nElement not found”); h=m-1;
} }
printf(“\nString not found”);
}

Sorting
Sorting is the process of arranging the elements in an order. The following are some of the sorting
techniques
a. Selection Sort b. Bubble Sort c. Insertion Sort d. Quick Sort

Selection Sort
In this technique, the position of the element with the least value is found and is interchanged with the
first element. The same procedure is continued with the remaining elements until the array is sorted.

Bubble Sort
Also called as exchange sort, it involves repeated comparisions and the smallest element is bubbled up to
the top.

Insertion sort
In this technique, the first two elements are sorted. Next, the algorithm inserts the third element into its
sorted position in relation to the first two elements. Then, it inserts the fourth element and the same
process is continued until all the elements are sorted.

Quick Sort
Build on the idea of partition, the general procedure is to select a value and then partition the array into
two sections such that all elements greater than or equal to the partition value are put one side and those
less than the value are put on the other. This procedure is continued for each remaining section until the
array is sorted.
/* Program to sort a numeric array */ quick_sort(int *a,int n)
#include<alloc.h> {
main() qs(a,0,n-1);
{ }
int *a,i,n; qs(int *a,int left,int right)
printf(“Enter the number of elements:”); {
scanf(“%d”,&n); int i,j,n,temp;
a=(int*)malloc(n*sizeof(int)); i=left;
for(i=0;i<10;i++) j=right;
{ n=a[(left+right)/2];
printf(“\n Enter a number:”); do
scanf(“%d”,&a[i]); {
} while(a[i]<no && i<right)
printf(“\nBefore Sorting:”); i++;
for(i=0;i<10;i++) while(no<a[j] && j>left)
printf(“%5d”,a[i]); j--;
selection_sort(a,n); if(i<=j)
/*bubble_sort(a,n); */ {
/*insertion_sort(a,n); */ temp=a[i];
/*quick_sort(a,n); */ a[i]=a[j];
printf(“\nAfter Sorting:”); a[j]=temp;
for(i=0;i<10;i++) i++;
printf(“%5d”,a[i]); j--;
} }
}while(i<=j);
if(left<j)
qs(a,left,j);
if(right>i)
qs(a,i,right);
}
selection_sort(int a[],int n) bubble_sort(int a[],int n)
{ {
int i,j,min,temp; int i,j,temp;
for(i=0;i<n-1;i++) for(i=0;i<n;i++)
{ for(j=n-1;j>i;j--)
min=i; f(a[j]<a[j-1])
for(j=i+1;j<n;j++) {
{ temp=a[j];
if(a[min]>a[j]) a[j]=a[j-1];
min=j; a[j-1]=temp;
} }
if(i!=min) }
{ insertion_sort(int *a,int n)
temp=a[i]; {
a[i]=a[min]; int i,j,temp;
a[min]=temp; for(i=1;i<n;i++)
} {
} temp=a[i];
} for(j=i-1;j>=0 && temp<a[j];j--)
a[j+1]=a[j];
a[j+1]=temp;
}
}

You might also like