PC Unit 3

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

Sri Manakula Vinayagar Engineering College Unit - 3 Programming in C

CollegeCollege
UNIT 3 - LOOPING AND ARRAYS

LOOPING

 WHILE LOOP

 DO WHILE LOOP

 FOR LOOP

 BREAK STATEMENT

 CONTINUE STATEMENT

 NESTED LOOP

ARRAYS

 ONE DIMENSIONAL ARRAY

 TWO-DIMENSIONAL ARRAYS

 MULTI-DIMENSIONAL ARRAY

 DYNAMIC ARRAYS

 CHARACTER ARRAYS AND STRING

 SORTING

 SEARCHING
PART – A (2 Marks)

Two mark questions with answer

1. Difference between break and continue statement?


Break Continue
Break statement takes the control to the Continue statement takes the control to
outside of the loop. the beginning of the loop.
It is also used in switch statement. It is used only in loop statement
It is always associated with if condition It is always associated with if condition
loops. loops.

2. Differentiate while and do while statement in C?


While Do while
It is top tested loop It is bottom tested loop
The condition is first tested , if the It executes the body once , after it
condition is true then the block is checks the condition , if it is true the
executed until the condition becomes body is executed until the condition
false . become false .
Loop will not be executed if the condition Loop will be executed atleast once
is false . eventhough the condition is false .

3. Write short notes on for loop?


It is repetitive control structure. It is used to execute a set of instruction repeatedly
until the condition becomes false.
Syntax :
for( initialize counter ;test condition ; increment or decrement counter)
{
…………..
Body of the loop;
………….
}
It has three parts
 Initialize counter: used to initialize counter variables.
 Test condition: used to test the condition.
 Increment/decrement: used to increment/decrement of counter variables.

4. Write short notes on goto statement?


Goto statement is mainly used to transfer the control unconditionally from one place to
another place in the program
It requires a label to identify the place to move the execution.
A label is a valid variable name and it must be ended with colon ( : )
Syntax:
goto label;
………..
……......
Label;

Label ;
…………
…………
Goto label;

5. What is looping statements? List out with examples?


Loop is defined as block of statements which are repeatedly executed for certain
number of times . In ‘C’ language there are two types of looping statements are available
they are:
 Conditional looping
 Unconditional looping
Conditional looping:
 While
 Do…while
 For
Unconditional looping :
 Switch ( ) case
 Break
 Continue
 goto

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”.

7. How strings are represented in language C?


String is the sequence of character or array of character enclosed within double quotes.
That string must terminate with null character (`\0`).
Eg.
char str[]=”super”;
The elements of the array are
str[0]=’s’;
str[1]=’u’;
str[2]=’p’;
str[3]=’e’;
str[4]=’r’;
str[5]=’\0’;

8.How is a character string declared?


 Character Array is Called as ‘String’
 Character Array is Declared Before Using it in Program
Syntax:
Char string_variable_name [size ];
Example:
Char city [30]; Char
name[20];

9.List out the types of string handling functions.


 strlen() - Used to find the length of a string.
 strcat() - Used to combine two strings.
 strrev() - Used to reverse a string.
 strcmp() - Used to compare a string with another string.
 strcpy() - Used to copy a string to another string.

10.Declare a float array of size 5 and assign 5 values to it. Syntax:


float float variable[size];
Example:
float sum[5]; float

sum=5.0f;

floatarray[100]={1.0f,5.0f,20.0f};

11.What is the purpose of the return statement?


The purpose of the return statement is, the return statement may or may not send back
any values to the main program (calling program). If it does, it can be done using the
return statement.
12.Define strlen() function.
strlen(), this function is used to count and return the number of character present in a
string.

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);

14.Define strcmp() function.


strcmp(), this function which compares two strings to find whether they are same or
different. If two strings are equal means it returns a zero otherwise numeric difference
between the non-matching characters.
Syntax:
strcmp(str1,str2);

15.Define strcpy() function.


strcpy(), this is used to copy the contents of a string to another strings.
Syntax:
strcpy(str1,str2);

16.What is an array? What are the classifications of an array?


Array means sequence of elements that share a common name with similar data types.
This is known as Array.

Types:
 One-dimensional array.
 Two-dimensional array and,
 Multi-dimensional array.

17.Write the features of arrays.


 An array is a derived data types. It is used to represent a collection of elements of the same
data type.
 The elements can be accessed with base address and the subscript defined for the position of
the element.
 The elements are stored in continuous memory location.
 The starting memory location is represented by the array name and it is known as the
base address of the array.

18.Define one – dimensional array.


The collection of data item can be stored under a one variable name using only one
subscript such a variable is called one – dimensional array.
Example:
int a[10];

19.Write example code to declare two dimensional array?,


An array with two subscripts is termed as two-dimensional array. A two dimensional array
enables us to store multiple rows of elements.
Example:
int a[10][10];

20.Give example for array initialization.


An array can be initialized at the time of declaration is known as compile time initialization.
Example:
int a[5]={5,8,7,4,1};

An array can be explicitly initialized at run time.


Example:
for(i=0;i<5;i++)
scanf(“%d”,&a[i]);
21.Define array. Give example.
Array means sequence of elements that share a common name with similar data types.
This is known as Array.
Example:
int rollno[66];
In this example we have declared an array of integer data type and named it “rollno” which
can store roll numbers of 66 students.

22.What is the value of b[0] in the following program?


void main()
{
int a[5]={1,3,6,7,0};
int *b;
b=&a[2];
}

Output: 6.

23.Why do you need to use array?


In many cases, we need to declare a set of variables that are of the same data type. Instead
of declaring each variable separately, we can declare all variables collectively in the format
of an array. Each variable, as an element of the array, can be accessed either through the
array element references or through a pointer that references the array.

24.What is the minimum index of an array?


The minimum index of a one-dimensional array is 0(zero), which marks the first element
of the array.

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).

25.List out the disadvantages of an array.


 The elements in the array must be same data types.
 The size of an array is fixed.
 If we need more space at run time, it is not possible to extend array.
 The insertion and deletion an operation is an array require shifting of elements which takes
time.

26.List out few characteristics of arrays.


 All the elements of an array share the same name and they are distinguished from one
another with help of an element number.
 The element number in an array plays major role for calling each element.
 An element of an array a[] can be assigned.
 The array elements are stored in continuous memory locations.

27.List out few types of sorting.


 Bubble sort.
 Selection sort.
 Insertion sort.
 Merge sort.
 Heap sort.
 Quick sort.

28.Declare a character array of size 5 and assign vowels to it.


Array Declaration with Initialization

type array_name[size] = {value_list};


For example:
char vowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};
29.Give some examples of string functions.

Strlen( )

char str1[20] = "BeginnersBook";


printf("Length of string str1: %d", strlen(str1));

Strcat()

char s1[10] = "Hello"; char


s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);

Strcpy()

char s1[30] = "string 1";


char s2[30] = "string 2 : I’m gonna copied into s1";
strcpy(s1,s2);
printf("String s1 is: %s", s1);

30. What is a null character? What is its use in string?


When declaring character arrays (strings), ‘\0’ (NULL) character is automatically added at
end. The ‘\0’ character acts as an end of character array.The length of a string can be
stored implicitly by using a special terminating character;
Often this is the null character (NUL), which has all bits zero, a convention used and
perpetuated by the popular C programming language. Hence, this representation is commonly
referred to as a C string

31.What are global and local variables?


A local variable is a variable whose existence is known only to a certain function or
program. Its scope is limited to a specific program block. For example, a variable declared
in the main program does not known to the function that is called in the main program.
Syntax:
void value(int a,int b)
{
int c,d; //local variables
}
A global variable is one whose existence is known throughout a c program. Such variables
are declared outside the main() and other functions of c. Typically, global declaration takes
place after the pre-processor statements in c.
Syntax:
int m=5,n=10; //global variables void
main()
{
int x,y; //local variables
}

PART – B (5 Marks & 10 Marks)

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;

/* while loop execution */


while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}

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

(ii) do…while loop:


The while loop makes a test of condition before the loop is executed. Body of the loop may
not be executed at all only if the condition is not satisfied at first attempt.

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

(iii) for loop:


For loop is another repetitive control structure and it is used to execute set of instructions
repeatedly until the condition becomes false.

Syntax: Flowchart

for(initialization;test
condition;increment/decr.counter)
{

Body of loop;
….

 Initialize counter: used to initialize counter variable


 Test condition: used to test the condition.
 Increment/decrement is used to increment/decrement the counter variable.

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

The syntax for a nested for loop statement in C is as follows:


for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows:
do
{
statement(s); do
{
statement(s);
}while( condition );

}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;

for(i=2; i<20; i++)


{
for(j=2; j <= (i/j); 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

Enter any number…10


Enter any number…15
Enter any number…25
Enter any number…10
Enter any number…50
Sum is …100

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

ONE DIMENSIONAL ARRAY


An array with a single subscript is known as one dimensional array.
It is otherwise known as single-subscribed (or) linear (or) one-dimensional arrays.

Example:
int number[5];

The memory representation of above example is given below in pictorial form.

Array name rollno[0] rollno[1] rollno[2] rollno[3] rollno[4]


Value
12 15 6 17 25
stored
Address 1024 1026 1028 1030 1032

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

a) Compile time initialization.


b) Run time initialization.
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32

a) Compile time Initialization


Initialization in made at the time of declaration (in the declaration part) is known as compile time
initialization. The general form of initialization of arrays is:

Syntax:
datatype array-name[size] = {list of values};

Example:
int rollno[3] = {26,32,12};

 The value of array are enclosed in braces and separated by commas.


 The values are assigned to the array by assignment operator (=).
 If the number of values in the list is less than the number of elements, then only that many
elements will be initialized.
 The remaining elements will be set to zero automatically.

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};

b) Run time Initialization

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];

The pictorial representation of the above example.

column column column


0 1 2

row 0 a[0][0] a[0][1] a[0][2]

row 1 a[1][0] a[1][1] a[1][2]

row 2 a[2][0] a[2][2] a[2][2]


Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32

Example :1 Matrix Transpose

/*Program for two dimensional array*/


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[3][3]; clrscr();
printf("Enter the First Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf("%d",&a[i][j]);
}

}
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

Example :2 Matrix Addition


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[3][3],b[3][3],c[3][3];
clrscr();
printf("Enter the First Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf("%d",&a[i][j]);
}

}
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

Example :3 Matrix Multiplication

#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

Enter the First Matrix 1


2 3
4 5 6
7 8 9
Enter the second Matrix 2 4
1
6 7 4
3 5 7
Matrix Multiplication 23
33 30
56 81 66
89 129 102

Initialization of two dimensional array:


There are two types of array initialization, they are given below.

Types:
c) Compile time initialization.
d) Run time initialization.

a) Compile time initialization.


The two dimensional array can be initialized at the time of declaration is known as Compile
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.

 Memory wastage will be there, if the array of large size is defined.


To delete an element of an array we need to traverse throughout array.

/* Example 1 for Multi Dimensional Array in C programming */


#include<stdio.h>
int main()
{
int tables, rows, columns;
int Employees[2][2][3] = { { {9, 99, 999}, {8, 88, 888} },
{ {225, 445, 665}, {333, 555, 777} } };
for (tables = 0; tables < 2; tables++)
{
for (rows = 0; rows < 2; rows++)
{
for (columns =0; columns < 3; columns++)
{
printf("Employees[%d][%d][%d] = %d\n", tables, rows, columns, Employees[tables][rows][columns]);
}
}
}
return 0;
}

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]);
}
}

Dynamic memory Allocation


The process of allocating memory at the time of execution or at the runtime, is called dynamic
memory location.
Two types of problem may occur in static memory allocation.
If number of values to be stored is less than the size of memory, there would be wastage of
memory.
If we would want to store more values by increase in size during the execution on assigned size
then it fails.
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
Allocation and release of memory space can be done with the
College 32 help of some library function
called dynamic memory allocation function. These library function are called as dynamic
memory allocation function. These library function prototype are found in the header file,
“alloc.h” where it has defined.
Function take memory from memory area is called heap and release when not required.

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;

printf("Enter number of elements: ");


scanf("%d", &n);
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College 32
ptr = (int*) malloc(n * sizeof(int));

// if memory cannot be allocated


if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

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

// deallocating the memory


free(ptr);

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.

8.HANDLING OF CHARACTER STRINGS

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’};

Each character is stored in one byte of memory.

Example:

g o o d \0
Sting
1004 1005 1006 1007 1008
Address

The operations that are performed on character strings are

 Reading and writing strings.


 Combining strings together.
 Copying one string to another.
 Comparing strings for equality.
 Extracting a portion of a string.

Declaring and Initializing String Variables


A string variable is any valid C variable name and is always declared as an array.
The general form of declaration of a string variable is

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.

C permits a character array to be initialized in either of the following two forms

char str[] = “THINK POSITIVE”;


char str[] = {‘T’, ‘H’, ‘I’,’N’,’K’, ‘ ‘, ‘P’, ‘O’, ‘S’, ‘I’,’T’,’I’,’V’,’E’, ‘\0’};

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.

Reading a Line of Text


 It is not possible to use scanf function to read a line containing more than one word.
 This is because the scanf terminates reading as soon as a space is encountered in the input.
 We can use the getchar() function repeatedly to read single character from the terminal,
using the function getchar(). Thus an entire line of text can be read and stored in an array.
Program
/*Program to read a line of text from terminal*/
#include<stdio.h>
#include<conio.h>
main()
{
char line[81],character;
int c=0;
clrscr();
printf(“Enter text. Press<Return>at end \n”);
do
{
character=getchar();
line[c]=character;
c++;
}
while(character != ‘\n’);
c=c-1;
line[c]=‘\0’;
printf(“\n %s \n”,line);
getch();
}

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.

All the string handling functions are prototyped in:


#include <string.h>
Byte
Description
String
strcpy() copies one string to another

strncpy() writes exactly n bytes/wchar_t, copying from


source or adding nulls
Sting
Manipulation strcat() appends one string to another

appends no more than n bytes/wchar_t from one


strncat()
string to another

strxfrm() transforms a string according to the current locale

strlen() returns the length of the string


strcmp() compares two strings
compares a specific number of bytes/wchar_t in
strncmp()
String two strings
Examination compares two strings according to the current
strcoll()
locale
finds the first occurrence of a byte/wchar_t in a
strchr()
string
finds the last occurrence of a byte/wchar_t in a
strrchr()
string
finds in a string the first occurrence of a
strspn()
byte/wchar_t not in a set
finds in a string the last occurrence of a
strcspn()
byte/wchar_t not in a set
finds in a string the first occurrence of a
strpbrk()
byte/wchar_t in a set
strstr() finds the first occurrence of a substring in a string

strtok() splits string into tokens

returns a string containing a message derived


Miscellaneous strerror()
from an error code

Following are the most commonly used string handling functions.

(i) strcat( ) Concatenates two strings.


(ii) strcmp( ) Compares two strings.
(iii) strcpy( ) Copies one string over another.
(iv) strlen( ) Finds the length of the string.
(v) strrev() Finds the reverse string

(i) strcat( ) Function – String concatenation


The strcat() function is used to joins two strings together.

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

(i) strcmp( ) Function – String Comparison


It is used to compare two strings identified by the arguments and has a value 0 if they are
equal.
Syntax:
strcmp(string1,string2);

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);

This assigns the content of string2 to string1.

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

(iii) strlen( ) Function – String Length


The process of finding the number of characters in a string with the help of
strlen(). This function counts and returns the number of characters in a given string.

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

V) strrev() Function – String Reverse


This function is used to find the reverse of the given string.
Syntax:
strrev(string);
Example:
str2=strrev(“success”);

The reverse of the string “success” is stored in str2 as “sseccus”


Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
clrscr();
Sri Manakula Vinayagar Engineering Unit-3 Programming in C
College printf(“Enter the string:”); 32
gets(str1);
str2=strrev(str1);
printf(“String1=%s\n”,str1);
printf(“String2=%s\n”,str2);
getch();
}
Output 1:
Enter the string: success String1= success String2= sseccus

Character conversions and testing: ctype.h


We conclude this chapter with a related library #include <ctype.h> which contains many useful
functions to convert and test single characters. The common functions are prototypes as follows:
Character testing
int isalnum(int c) True if c is alphanumeric.
int isalpha(int c) True if c is a letter.
int isascii(int c) True if c is ASCII .
int iscntrl(int c) True if c is a control character.
int isdigit(int c) True if c is a decimal digit
int isgraph(int c) True if c is a graphical character.
int islower(int c) True if c is a lowercase letter
int isprint(int c) True if c is a printable character
int ispunct (int c) True if c is a punctuation character.
int isspace(int c) True if c is a space character.
int isupper(int c) True if c is an uppercase letter.
int isxdigit(int c) True if c is a hexadecimal digit

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

Enter the number of terms: 5

Enter the elements of the array:


12 10 14 5 16

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:

 Linear Search or Sequential Search


 Binary Search
Linear Search or Sequential Search - Find whether a value is exist in a given array. If it is exist then
return the current position. In this algorithm we check the value one by one in given list.

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

You might also like