PC Unit 3
PC Unit 3
PC Unit 3
CollegeCollege
UNIT 3 - LOOPING AND ARRAYS
LOOPING
WHILE LOOP
DO WHILE LOOP
FOR LOOP
BREAK STATEMENT
CONTINUE STATEMENT
NESTED LOOP
ARRAYS
TWO-DIMENSIONAL ARRAYS
MULTI-DIMENSIONAL ARRAY
DYNAMIC ARRAYS
SORTING
SEARCHING
PART – A (2 Marks)
Label ;
…………
…………
Goto label;
6.What is string? String is the sequence of character or array of character enclosed within double
quotes.
That string must terminate with null character (`\0`).
Eg. “super”.
sum=5.0f;
floatarray[100]={1.0f,5.0f,20.0f};
Syntax:
len=strlen(string);
13.Define strrev() function.
strrev(), this function is used to reverse a string. This function takes and returns only
one argument.
Syntax:
strrev(str);
Types:
One-dimensional array.
Two-dimensional array and,
Multi-dimensional array.
Output: 6.
Example:
int a[8];
The first element of the array is a[0]. Likewise, for a multidimensional array, the minimum
index of each dimension starts at 0(zero).
Strlen( )
Strcat()
Strcpy()
1.LOOPING STATEMENTS
A loop is defined as a block of statements which are repeatedly executed for certain
number of times. A loop can either be a pre-test loop or be a post-test loop i.e.
entry controlled loop or exit controlled loop.
The following steps are should need to construct the looping concept in a program.
Initialization of a counter variable
o It is a variable used in the loop
Test condition
Body of the loop
o Block of statements depends on the test condition
Updating the counter variable - Example: Increment/Decrement
There are three types of looping, namely:
1. while loop
2. do-while loop
3. for loop
(i)While loop:
It is an entry control loop statement. The test condition is evaluated and if it is true, the body of the
loop is executed. The test condition is repetitively checked and if it is true the body is executed.
The process of execution of the body will continue till the test condition becomes true. The
control is transferred out of the loop if the test condition becomes false.
Program 1:
Syntax: Flowchart
while(condition)
{
….
Body of the loop;
….
}
….
Example:
#include<stdio.h>
void main()
{
int i=1;
while(i<=10)
{
printf(“%d\n”,i);
i++;
}
printf(“Finished”);
}
Output:
1
2
3
4
5
6
7
8
9
10
Finished
Example:
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Syntax: Flowchart
do
{
…..
Body of loop;
…..
}while(condition);
Example #include<stdio.h>
void main()
{
int i=1;
do
{
printf(“%d”,i);
i++;
}while(i<=10);
}
Output:
1 2 3 4 5 6 7 8 9 10
Example:
#include <stdio.h>
int main ()
{
/* local variable definition */ int a = 10;
/* do loop execution */
do
{
printf("value of a: %d\n", a);
a ++;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Syntax: Flowchart
for(initialization;test
condition;increment/decr.counter)
{
…
Body of loop;
….
Example:
#include<stdio.h>
void main()
{
for(int i=1;i<=5;i++)
{
printf(“%d\n”,i);
}
}
Output:
1
2
3
4
5
Example:
#include <stdio.h>
int main ()
{
/* for loop execution */
for(int a = 10; a < 20; a++)
{
printf("value of a: %d\n", a);
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
2.NESTED LOOP
C programming language allows to use one loop inside another loop.
Syntax
}while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type of loop.
For example, a for loop can be inside a while loop or vice versa.
Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100:
#include <stdio.h>
int main ()
{
/* local variable definition */
int i, j;
if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
3.JUMPS IN LOOPS
UNCONDITIONAL LOOP
(i) Break
(ii) Continue
(iii) Goto
break statement:
1. It is used to terminate the loop. When the keyword break is used inside any ‘C’
loop,control automatically transferred to first statement after the loop.
2. A break is usually associated with an if statement.
Syntax:
break;
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int i; for(i=1;i<=10;i++)
{
if(i==6) break;
printf(“%d”,i);
}
}
Output:
12345
Continue statement
It is mainly used to take the control to the beginning of the loop, for these purposes
continue statement is used.
When the statements continue is used inside any ‘C’ loop, control automatically passes to
the beginning of the loop.
It is also associated with if statement.
Syntax:
continue;
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int i,n,sum==0;
for(i=1;i<=5;i++)
{
print(“Enter any number…\n”);
scanf(“%d”,&n);
if(n<0)
continue;
else
sum=sum+n;
}
printf(“sum is…%d”,sum);
}
Output:
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
Goto statement
It is used to transfer control unconditionally from one place to another place.
A goto statement can cause program control almost anywhere in the program
unconditionally.
It requires a label to identify the place to move the execution.
A label is a valid variable name and must be ended with colon (:).
Syntax:
goto label;
………
………
label:
label:
…….
…….
goto label;
Program:
#include<stdio.h>
main()
{
int a,b;
printf(“Enter the numbers”);
scanf(“%%d”,&a,&b);
if(a==b)
goto equal;
else
{
printf(“\n A and B are not equal”);
exit(0);
}
equal:
printf(“A and B are equal”);
}
Output:
1. Enter the numbers 3 3
A and B are equal
2. Enter the numbers 3 4
A and B are not equal
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
4. ARRAY
INTRODUCTION
An array is a group of related data items that share a common name. The value is indicated by
writing a number called index number or subscript in brackets after the array name.
Example:
int salary[10];
PROPERTIES OF AN ARRAY
All the elements of an array share the same name and they are distinguished from one
another with the help of an element number.
The element number in an array plays major role for calling each element.
The type of an array is the data type of its elements.
The array elements are stored in continuous memory locations.
The location of an array is the location of its first element.
The length of an array is the no. of data elements in the array.
The size of an array is the length of the array times the size of an elements.
TYPES OF ARRAY
(i) One dimensional array
(ii) Two dimensional array
(iii) Multi dimensional array
Example:
int number[5];
DECLARATION OF ARRAYS
The general form of array declaration is
Synatx:
type variable-name[size];
The type specifies the type of element, such as int, float, or char.
The size indicates the maximum number of elements that can be stored inside the array.
Example:
float height[50];
int group[10];
char name[10];
INITIALIZATION OF ARRAYS
We can also initialize the elements of arrays like an ordinary variable initialization.
An array can be initialized in two way, they are
Syntax:
datatype array-name[size] = {list of values};
Example:
int rollno[3] = {26,32,12};
We can use the word ‘static’ before type declaration. This declares the variable as a
static variable.
Example:
static int counter[] = {1,1,1};
for(i =0; i < 100; i = i+1)
{
if (i < 50)
sum[i] = 0.0;
else
sum[i] = 1.0;
}
……….
……….
type variable-name[size];
static type array-name[size] = {list of values};
When the users have to initialize more number of elements means it is difficult to use
compile time initialization. To avoid this situation the user can initialize elements in run time.
Program
/*Program showing one-dimensional array*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],sum=0,i,n;
clrscr();
printf(“Enter no. of terms:”);
scanf(“%d”,&n);
printf("Enter %d integer numbers\n",n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("The sum of given numbers is : %d\n",sum);
getch();
}
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
The entire sorting & searching algorithm must use the one-dimensional array.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],i,n,large,small;
clrscr();
printf("Enter size of the array");
scanf("%d",&n);
printf("Enter elements in the array:");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
large=small=a[0];
for(i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("\nLarge element = %d",large);
printf("\nSmall element =%d",small);
getch();
}
Output
Enter size of the array: 10
Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10
Large element = 100
Small element = -10
5.TWO-DIMENSIONAL ARRAYS
Arrays whose elements are specified by two subscripts are called Two-dimensional arrays
(or) double-subscripted arrays.
Syntax:
datatype array-name[row_size][column_size];
Example:
int a[3][3];
}
printf("Transpose Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d\t",a[j][i]);
}
printf(“\n”);
}
getch();
}
Output
Enter the First Matrix
1 2 3
2 3 4
5 8 7
Transpose Matrix
12 5
2 3 8
3 4 7
}
printf("Enter the Second Matrix");
for(i=1;i<=3;i++)
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
{
College 32
for(j=1;j<=3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("Display Addition Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d \t",c[i][j]);
}
printf("\n");
}
getch();}
Output
Enter the First Matrix 1
2 3
2 1 2
3 1 1
Enter the second Matrix 1 2
3
2 1 2
3 1 1
Display Addition matrix 2
4 6
4 2 4
6 2 2
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[2][2], b[2][2],c[2][2],i,j;
int i,j,k;
clrscr();
printf("Enter first matrix:\n" ); for(
i=1;i<=3;i++)
{
for( j=1;j<=3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter second matrix:\n");
for(i=1;i<=3;i++)
{
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College for(j=1;j<=3;j++) 32
{
scanf("%d",&b[i][j]);
}
}
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
c[i][j]=0;
for(k=1;k<=3;k++)
{
c[i][j] =c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("Matrix Multiplication Is: \n");
for(i=1;i<=3;i++)
{
for (j=1;j<=3;j++)
{
printf("%d\n",c[i][j]);
}
}
getch();}
Output
Types:
c) Compile time initialization.
d) Run time initialization.
Example:
int a[2][3]={1,1,1,3,3,3};
(or) int
a[2][3]={
{1,1,1},
{3,3,3}
};
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
This statement will initialize the elements of first row to 1 and second row to 3.
int a[2][]={1,1,1,3,3,3};
int a[][]={1,1,1,3,3,3};
The above two examples will never work. To make the above two initialization in better
manner means we must mention the column size then only the compiler knows where the first row
ends.
The row size is optional if we initialize the array in the declaration part itself.
b) Run time initialization.
An array can be explicitly initialized at run time by using scanf() function.
Example:
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
}
}
Example:
Simple program for printing the elements of 2D array.
#include <stdio.h>
void main()
{
int score[3][2]= {10,20,30,40,50,60};
int i,j;
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<2;j++)
{
printf("%d\t",score[i][j]);
}
}
}
Output:
10 20
30 40
50 60
6.MULTIDIMENSIONAL ARRAY
C allows arrays of three or more dimensions. The exact limit is determined by the compiler.
The general form of a multidimensional array is
Syntax:
datatype array_name[s1][s2][s3]…s[m];
Example:
int s[3][5][12];
float t[5][4][5][3];
Advantages of arrays
It is capable of storing many elements at a time.
It allows random access of elements.
Disadvantages of arrays
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
The elements in the array must be same data type.
College 32
Predetermining the size of array is must.
Example:2
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, k;
int arr[3][3][3]=
{
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
clrscr();
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College printf("\n"); 32
}
printf("\n");
}
getch();
}
Output:
11 12 13
14 15 16
17 18 19
21 22 23
24 25 26
27 28 29
31 32 33
34 35 36
37 38 39
7. DYNAMIC ARRAY
Array is the example where memory is organized in contiguous way, in the dynamic memory
allocation function used such as malloc(), calloc(), realloc() always made up of contiguous way
and as usual we can access the element in two ways as:
Example:
#include<stdio.h>
#include<alloc.h>
void main()
{
printf(“enter the no.of values”);
scanf(“%d”,&n);
p=(int*)malloc(n*size of int);
If(p==null)
printf(“not available memory”); exit();
}
for(i=0;i<n;i++)
{
printf(“enter an integer”);
scanf(“%d”,&p[i]);
for(i=0;i<n;i++)
{
printf(“%d”,p[i]);
}
}
Pointer has important role in the dynamic memory allocation to allocate memory.
malloc():
This function use to allocate memory during run time, its declaration is void*malloc(size);
malloc ()
returns the pointer to the 1st byte and allocate memory, and its return type is void, which can
be type cast such as:
int *p=(datatype*)malloc(size)
If memory location is successful, it returns the address of the memory chunk that was allocated
and it returns null on unsuccessful and from the above declaration a pointer of type(datatype)
and size in byte.
And datatype pointer used to typecast the pointer returned by malloc and this typecasting is
necessary since, malloc() by default returns a pointer to void.
Example int*p=(int*)malloc(10);
So, from the above pointer p, allocated IO contigious memory space address of 1st
byte and is stored in the variable.
We can also use, the size of operator to specify the the size, such as
*p=(int*)malloc(5*size of int) Here, 5 is the no. of data.
Moreover , it returns null, if no sufficient memory available , we should always check the malloc
return such as, if(p==null)
printf(“not sufficient memory”);
Example:
/*calculate the average of mark*/
Void main()
{
int n , avg,i,*p,sum=0;
printf("enter the no. of marks ”);
scanf(“%d”,&n);
p=(int *)malloc(n*size(int));
if(p==null)
printf(“not sufficient”); exit();
}
for(i=0;i<n;i++)
scanf(“%d”,(p+i));
for(i=0;i<n;i++)
Printf(“%d”,*(p+i));
sum=sum+*p;
avg=sum/n;
printf(“avg=%d”,avg);
calloc()
Similar to malloc only difference is that calloc function use to allocate multiple block of memory .
two arguments are there
1st argument specify number of blocks
2nd argument specify size of each block.
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
Example:-
College 32
int *p= (int*) calloc(5, 2);
int*p=(int *)calloc(5, size of (int));
Another difference between malloc and calloc is by default memory allocated by malloc contains
garbage value, where as memory allocated by calloc is initialised by zero(but this initialisation)
is not reliable.
realloc()
The function realloc use to change the size of the memory block and it alter the size of the
memory block without loosing the old data, it is called reallocation of memory.
It takes two argument such as; int*ptr=(int *)malloc(size);
int*p=(int *)realloc(ptr, new size);
The new size allocated may be larger or smaller.If new size is larger than the old size, then old
data is not lost and newly allocated bytes are uninitialized. If old address is not sufficient then
starting address contained in pointer may be changed and this reallocation function moves content
of old block into the new block and data on the old block is not lost.
Example:
#include<stdio.h>
#include<alloc.h>
void main()
int i,*p;
p=(int*)malloc(5*size of (int));
if(p==null)
{
printf(“space not available”);
exit();
printf(“enter 5 integer”);
for(i=0;i<5;i++)
{
scanf(“%d”,(p+i));
int*ptr=(int*)realloc(9*size of (int) );
if(ptr==null)
{
printf(“not available”);
exit();
}
printf(“enter 4 more integer”);
for(i=5;i<9;i++)
scanf(“%d”,(p+i));
for(i=0;i<9;i++)
printf(“%d”,*(p+i));
}
Example:
/ *Program to calculate the sum of n numbers using malloc*/
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
return 0;
}
Output
Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156
free()
Function free() is used to release space allocated dynamically, the memory released by free() is
made available to heap again. It can be used for further purpose.
Syntax for free declaration .
void(*ptr)
Or
free(p)
When program is terminated, memory released automatically by the operating system. Even we
don’t free the memory, it doesn’t give error, thus lead to memory leak. We can’t free the memory,
those didn’t allocated.
Introduction
The group of character, digits and symbols enclosed within quotation marks are called as
string; otherwise strings are array of characters. Null character (‘\0’) is used to mark the end of
the string.
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
Example:
char name[]={‘g’,’o’,’o’,’d’,’\0’};
Example:
g o o d \0
Sting
1004 1005 1006 1007 1008
Address
Syntax:
char string_name[size];
Example:
char city[10];
char name[30];
When the compiler assigns a character string to a character array, it automatically supplies a null
character (‘\0’) at the end of the string. Therefore, the size should be equal to the maximum
number of characters in the string plus one.
Reading Words
The familiar input function scanf() can be used with %s format specification to read in a
string of characters.
Example:
char address[15];
scanf(“%s”,address);
Program
/*Reading a series of words using scanf function*/
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College #include<stdio.h> 32
#include<conio.h>
main()
{
char w1[40],w2[40],w3[40],w4[40];
clrscr();
printf(“Enter text:\n”);
scanf(“%s%s%s%s”,w1,w2,w3,w4);
printf(“\n”);
printf(“word1 = %s \n word2 = %s \n”,w1, w2);
printf(“word3 = %s \n word4 = %s \n”,w3, w4);
getch();
}
Output
Enter text:
Hello How are you
word1=Hello
word2=How
word3=are
word4=you
Note: scanf() function terminates its input on the first white space it finds.
We have used extensively the printf() function with %s format to print strings to the
screen. The format %s can be used to display an array of characters that is terminated by the null
character.
Example:
printf(“%s”, name);
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
9.STRING - HANDLING FUNCTIONS
C library supports a large number of string-handling functions that can be used to carry out
many of the string manipulation activities.
Syntax:
strcat(string1,string2);
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
String1 and String2 are character type arrays or string constant
Example:
strcat(“THINK “, “POSITIVE”);
strcat(strcat(string1,string2),string3);
Here three strings are concatenated and the result is stored in string1.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50]; clrscr();
printf(“Enter the first string:”);
gets(str1);
printf(“Enter the second string:”);
gets(str2); strcat(str1,str2);
printf(“Result=%s”,str1); getch();
getch();
}
Output:
Enter the first string: Computer
Enter the second string:
Programming Result=Computer
Programming
Before Execution
str1 C o m p u t e r
str2 P r o g r a m m i n g
After Execution
str1 C o m p u t e r P r o g r a m m i n g
str2 P r o g r a m m i n g
Example:
strcmp(name1,name2);
strcmp(name1,”john”;
strcmp(“ram”, “rom”);
Comparison Table
S.No Value Meaning
1 Less than Zero String1 is less than string2
2 Zero Strings are equal
3 Greater than Zero String1 is greater than string 2
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char
str1[50],str2[50];
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College int n; 32
clrscr();
printf(“Enter the first string:”);
gets(str1);
printf(“Enter the second string:”);
gets(str2);
n=strcmp(str1,str
2); if(n==0)
printf(“Strings are equal”);
else
printf(“Strings are not equal”);
getch();
}
Output 1:
Enter the first string: computer
Enter the second string:
Programming Strings are not
equal
Output 2:
Enter the first string:
computer Enter the second
string: computer Strings are
equal
(ii) strcpy( ) Function – String Copy
This function works almost like a string assignment operator. It takes the form
Syntax:
strcpy(string1,string2);
Example:
strcpy(str1, “SUPER”);
strcpy(str1,str2);
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char
str1[50],str2[50],str3[50];
int n;
clrscr();
printf(“Enter the first
string:”); gets(str1);
strcpy(str2,”SUPER”);
strcpy(str3,str1);
printf(“String1=%s\n”,str
1);
printf(“String2=%s\n”,str
2);
printf(“String3=%s\n”,str
3); getch();
}
Output 1:
Enter the first string:
computer String1=
Computer
String2= SUPER
String3=
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College Computer 32
Syntax:
n = strlen(string);
Program
/*Illustration of string-handling functions*/
#include<stdio.h>
#include<string.h>
#include<conio.h>
main()
{
char s1[20],s2[20],s3[20];
int
x,len1,len2,len3;
clrscr();
printf(“Enter two string constants \n”);
scanf(“%s%s”,s1,s2);
x=strcmp(s1,s2);
if(x!= 0)
printf(“Strings are not equal \n”);
strcat(s1, s2);
else
printf(“Strings are equal \n”);
strcpy(s3,s1);
len1=strle
n(s1);
len2=strle
n(s2);
len3=strle
n(s3);
printf(“\ns1=%s\tlength=%dcharacters\n”,s1,len1);
printf(“\ns2= %s \tlength=%dcharacters\n”,s2, len2);
printf(“\ns3=%s\tlength=%dcharacters\n”,s3,len3);
}
OUTPUT
Enter two string constants
New York
Strings are not equal
s1=New York length=7 characters
s2=York length=4 characters
s3=New York length=7 characters
Character Conversion
int toascii(int c) Convert c to ASCII .
tolower(int c) Convert c to lowercase.
toupper(int c) Convert c to uppercase
Example:
# include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
char str1[20];
int opt,len;
printf("\n MAIN MENU");
printf("\n 1. Convert string into upper case");
printf("\n 2. Reverse the string");
printf("\n 3. Copy one string into another string");
printf("\n 4.Compute length of string ");
printf("Enter string ");
scanf("%s", &str);
printf("Enter your choice");
scanf("%d",&opt);
switch(opt)
{
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
case 1: strupr(str);
printf("The string in uppercase is :%s ",str);
break;
case 2: strrev(str);
printf("The reverse of string is : %s",str);
break;
case 3: strcpy(str1,str);
printf("New copied string is : %s",str1);
break;
case 4: len=strlen(str);
printf("The length of the string is : %s",len); break;
default: printf("You have entered a wrong choice");
}
10.SORTING
Arranging in an ordered sequence is called "sorting". Sorting is a common operation in many
applications, and efficient algorithms to perform it have been developed.
Common sorting algorithms
Bubble/Shell sort: Exchange two adjacent elements if they are out of order. Repeat until array is
sorted.
Insertion sort: Scan successive elements for an out-of-order item, then insert the item in the proper
place.
Selection sort: Find the smallest (or biggest) element in the array, and put it in the proper place.
Swap it with the value in the first position. Repeat until array is sorted.
Quick sort: Partition the array into two segments. In the first segment, all elements are less than or
equal to the pivot value. In the second segment, all elements are greater than or equal to the pivot
value. Finally, sort the two segments recursively.
Merge sort: Divide the list of elements in two parts, sort the two parts individually and then merge it.
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them if they are
not in the intended order.
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
Example:
#include<stdio.h>
void main()
{
int a[20], n, temp, i, j;
printf("Enter the number of terms: ");
scanf("%d",&n);
printf("Enter the elements of the array:");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
for(i=0; i<n; i++)
{
for(j=0; j<n-i-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("After Sorting:\n");
for(i=0; i<n; i++)
{
printf("%d\t", a[i]);
}
}
Output
After Sorting:
5 10 12 14 16
11.SEARCHING : It check for an element or retrieve an element from any data structure where the
data is stored. Based on the type of search operation, there are generally two algorithms defined in C:
Binary Search - Search in the given sorted elements. In this algorithm we divide sorted elements from
middle and check the lie between which part. Same process we try until the all element not read.
Linear search is a very simple search algorithm. In this type of search, a sequential search is made
over all items one by one. Every item is checked and if a match is found then that particular item is
returned, otherwise the search continues till the end of the data collection.
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
Example:
#include<stdio.h>
#inlcude<conio.h>
main()
{
int i,n,a[30],key,flag=100;
clrscr();
printf(“Enter the no. of terms:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i];
}
printf(“Enter the search element:”);
scanf(“%d”,&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf(“The searching element is %d present in location %d”,key,i);
flag=i;
}
}
if(flag==i)
printf(“The searching element is not present”);
getch();
}
Output 1
Enter the no. of terms:5
10 12 14 16 18
Enter the search element:18
The searching element is 18 present in location 5
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32