You are on page 1of 33

Arrays

In C language, arrays are referred to as Derived data types. An array is defined as finite
sequence collection of homogenous data, stored in contiguous memory locations.

Here the words,

 finite means data range must be defined.


 ordered means data must be stored in continuous memory addresses.
 homogenous means data must be of similar data type.

Example where arrays are used,

 to store list of Employee or Student names,


 to store marks of a students,
 to store list of numbers or characters etc.

Since arrays provide an easy way to represent data, it is classified amongst the data structures in
C. Other data structures in c are structure, lists, queues and trees. Array can be used to
represent not only simple list of data but also table of data in two or three dimensions.

Arrays are of two types:

1. One-dimensional arrays
2. Multidimensional arrays

Declaring an Array(1-D)
Like any other variable, arrays must be declared before they are used. General form of array
declaration is,

data-type variable-name[size];

for example :
int arr[10];

Here int is the data type, arr is the name of the array and 10 is the size of array. It means array
arr can only contain 10 elements of int type. Index of an array starts from 0 to size-1 i.e first
element of arr array will be stored at arr[0] address and last element will occupy arr[9].

Memory Representation of 1-D Array:


After declaring the array variable the memory is allocated as follows.

Example-1: int A[5];


Let us assume starting address of the array is 100.

A[0] A[1] A[2] A[3] A[4]


index 0 1 2 3 4
value
Memory Locations 100 102 104 106 108
In the above example the values of the array are empty because we can’t initialize the array.

Example-2: char B[5];


Let us assume starting address of the array is 100.
B[0] B[1] B[2] B[3] B[4]
index 0 1 2 3 4
value
Memory Locations 100 101 102 103 104
Size of an array=Total number of elements * size of data type.
Size of A=10(5*2) and size of B=5(5*1).
After initializing the array variable the memory is allocated as follows.

Example: int A[5]={3,4,2,6,5};

In the above statement the array A is declared and initialized then the memory mapping will be
looking as follows. Let us assume starting address of the array is 100.

A[0] A[1] A[2] A[3] A[4]


index 0 1 2 3 4
value 3 4 2 6 5
Memory Locations 100 102 104 106 108

Initialization of an Array(1-D)
After an array is declared it must be initialized. Otherwise, it will contain garbage value (any
random value). An array can be initialized at either compile time or at runtime.

Compile time Array initialization:-

Compile time initialization of array elements is same as ordinary variable initialization. The
general form of initialization of array is,

type array-name[size] = { list of values };

int marks[4]={ 67, 87, 56, 77 }; //integer array initialization

float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization

int marks[4]={ 67, 87, 56, 77, 59 }; //Compile time error

One important things to remember is that when you will give more initializer than declared array
size than the compiler will give an error.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
int arr[]={2,3,4}; //Compile time array initialization
for(i=0 ; i<3 ; i++) {
printf("%d\t",arr[i]);
}
getch();
}

Output

2 3 4

Runtime Array initialization:-

An array can also be initialized at runtime using scanf() function. This approach is usually used
for initializing large array, or to initialize array with user specified values. Example,

#include<stdio.h>
#include<conio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i=0;i<4;i++)
{
scanf("%d",&arr[i]); //Run time array initialization
}
for(j=0;j<4;j++)
{
printf("%d\n",arr[j]);
}
getch();
}

Accessing Array Elements(1-D)

An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example −

double salary = balance[9];

The above statement will take the 10th element from the array and assign the value to salary
variable. The following example Shows how to use all the three above mentioned concepts viz.
declaration, assignment, and accessing arrays −

#include <stdio.h>

int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}

/* output each array element's value */


for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}

return 0;
}

When the above code is compiled and executed, it produces the following result −

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Example of array in C programming


/* C program to find the sum marks of n students using arrays */

#include <stdio.h>
int main(){
int marks[10],i,n,sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;++i){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}

Output:
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
sum=45

Basic operations on arrays:

Following operations can be performed on arrays:

1. Traversing
2. Searching
3. Insertion
4. Deletion
5. Sorting
6. Merging
1. Traversing: It is used to access each data item exactly once so that it can be processed.
E.g.
We have linear array A as below:

0 1 2 3 4
10 20 30 40 50

Here we will start from beginning and will go till last element and during this process we will
access value of each element exactly once as below:

A [0] = 10
A [1] = 20
A [2] = 30
A [3] = 40
A [4] = 50

2. Searching: It is used to find out the location of the data item if it exists in the given
collection of data items.
E.g.
We have linear array A as below:

0 1 2 3 4
15 50 35 20 25

Suppose item to be searched is 20. We will start from beginning and will compare 20 with each
element. This process will continue until element is found or array is finished. Here:

1) Compare 20 with 15
20 # 15, go to next element.

2) Compare 20 with 50
20 # 50, go to next element.

3) Compare 20 with 35
20 #35, go to next element.

4) Compare 20 with 20
20 = 20, so 20 is found and its location is 4.

3. Insertion: It is used to add a new data item in the given collection of data items at specified
location.
E.g.
We have linear array A as below:

0 1 2 3 4
10 20 50 30 15
New element to be inserted is 100 and location for insertion is 3. So shift the elements from 5th
location to 3rd location downwards by 1 place. And then insert 100 at 3rd location. It is shown
below:

4. Deletion: It is used to delete an existing data item from the given collection of data items.
E.g.
We have linear array A as below:

0 1 2 3 4 5
10 20 50 40 25 60

The element to be deleted is 50 which is at 3rd location. So shift the elements from 4th to 6th
location upwards by 1 place. It is shown below:

After deletion the array will be:


1 2 3 4 5 6
10 20 40 25 60
5. Sorting: It is used to arrange the data items in some order i.e. in ascending or descending
order in case of numerical data and in dictionary order in case of alphanumeric data.
E.g.
We have linear array A as below:

0 1 2 3 4
10 50 40 20 30

After arranging the elements in increasing order by using a sorting technique, the array will be:

0 1 2 3 4
10 20 30 40 50

6. Merging: It is used to combine the data items of two sorted files into single file in the sorted
form
We have sorted linear array A as below:

0 1 2 3 4 5
10 40 50 80 95 100

And sorted linear array B as below:

0 1 2 3
20 35 45 90

After merging merged array C is as below:

0 1 2 3 4 5 6 7 8 9
10 20 35 40 45 50 80 90 95 100

Limitations of Array:

A. Static Data

1. Array is Static data Structure


2. Memory Allocated during Compile time.
3. Once Memory is allocated at Compile Time it Cannot be Changed during Run-time

B. Can hold data belonging to same Data types

1. Elements belonging to different data types cannot be stored in array because array data
structure can hold data belonging to same data type.
2. Example : Character and Integer values can be stored inside separate array but cannot be
stored in single array
C. Inserting data in Array is Difficult

1. Inserting element is very difficult because before inserting element in an array we have to
create empty space by shifting other elements one position ahead.
2. This operation is faster if the array size is smaller, but same operation will be more and more
time consuming and non-efficient in case of array with large size.

D. Deletion Operation is difficult

1. Deletion is not easy because the elements are stored in contiguous memory location.
2. Like insertion operation , we have to delete element from the array and after deletion empty
space will be created and thus we need to fill the space by moving elements up in the array.

E. Bound Checking

1. If we specify the size of array as ‘N’ then we can access elements upto ‘N-1’ but in C if we try to
access elements after ‘N-1’ i.e Nth element or N+1th element then we does not get any error
message.
2. Process of Checking the extreme limit of array is called Bound Checking and C does not perform
Bound Checking.
3. If the array range exceeds then we will get garbage value as result.

F. Shortage of Memory

1. Array is Static data structure. Memory can be allocated at compile time only Thus if after
executing program we need more space for storing additional information then we cannot
allocate additional space at run time.
2. Shortage of Memory , if we don’t know the size of memory in advance

G. Wastage of Memory

1. Wastage of Memory , if array of large size is defined

Array Applications :
Array is used for different verities of applications. Array is used to store the data or values of
same data type. Below are the some of the applications of array

A. Stores Elements of Same Data Type

Array is used to store the number of elements belonging to same data type.

int arr[30];

Above array is used to store the integer numbers in an array.

arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Similarly if we declare the character array then it can hold only character. So in short character
array can store character variables while floating array stores only floating numbers.

B. Array Used for maintaining multiple variable names using single name

Suppose we need to store 5 roll numbers of students then without declaration of array we need to
declare following –

int roll1,roll2,roll3,roll4,roll5;

1. Now in order to get roll number of first student we need to access roll1.
2. Guess if we need to store roll numbers of 100 students then what will be the procedure.
3. Maintaining all the variables and remembering all these things is very difficult.

Consider the Array:

int roll[5];

So we are using array which can store multiple values and we have to remember just single
variable name.

C. Array Can be Used for Sorting Elements

We can store elements to be sorted in an array and then by using different sorting technique we
can sort the elements.

Different Sorting Techniques are :

1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Bucket Sort

D. Array Can Perform Matrix Operation

Matrix operations can be performed using the array. We can use 2-D array to store the matrix.
[box]Matrix can be multi-dimensional [/box]

E. Array Can be Used in CPU Scheduling

F. Array Can be Used in Recursive Function

When the function calls another function or the same function again then the current values are
stores onto the stack and those values will be retrieving when control comes back. This is similar
operation like stack.

TWO- DIMENSIONAL ARRAYS

Definition:- C language supports multidimensional arrays. The simplest form of the


multidimensional array is the two-dimensional array.

Two-dimensional array is declared as follows,


type array-name[row-size][column-size]

Example :
int a[3][4];

The above array can also be declared and initialized together. Such as,

int arr[][3] = {
{0,0,0},
{1,1,1}
};

Declaration of 2-D arrays:


The simplest form of multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array
of size [x][y], you would write something as follows −

type arrayName [ x ][ y ];

Where type can be any valid C data type and arrayName will be a valid C identifier. A two-
dimensional array can be considered as a table which will have x number of rows and y number
of columns. A two-dimensional array a, which contains three rows and four columns can be
shown as follows −
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where
'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in
'a'.

Initializing Two-Dimensional Arrays

Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to the previous example −

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements

An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example −

int val = a[2][3];

The above statement will take the 4th element from the 3rd row of the array. You can verify it in
the above figure. Let us check the following program where we have used a nested loop to
handle a two-dimensional array −

#include <stdio.h>

int main () {

/* an array with 5 rows and 2 columns*/


int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */


for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {


printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

return 0;
}

When the above code is compiled and executed, it produces the following result −

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

MULTI- DIMENSIONAL ARRAYS:


C allows for arrays of two or more dimensions. A two-dimensional (2D) array is an array of
arrays. A three-dimensional (3D) array is an array of arrays of arrays.

In C programming an array can have two, three, or even ten or more dimensions. The maximum
dimensions a C program can have depends on which compiler is being used.

More dimensions in an array means more data be held.

Declaration of Multidimensional Array

A multidimensional array is declared using the following syntax:

type array_name[d1][d2][d3][d4]………[dn];

Where each d is a dimension, and dn is the size of final dimension.

Examples:

1. int table[5][5][20];
2. float arr[5][6][5][6][5];

In Example 1:

 int designates the array type integer.


 table is the name of our 3D array.
 Our array can hold 500 integer-type elements. This number is reached by multiplying the value
of each dimension. In this case: 5x5x20=500.

In Example 2:

 Array arr is a five-dimensional array.


 It can hold 4500 floating-point elements (5x6x5x6x5=4500).

A 3D array is essentially an array of arrays of arrays: it's an array or collection of 2D arrays and
a 2D array is an array of 1D array.

3D Array Conceptual View


3D array memory map

Initializing a 3D Array in C

Like any other variable or array, a 3D array can be initialized at the time of compilation. By
default, in C, an uninitialized 3D array contains “garbage” values, not valid for the intended use.

Let’s see a complete example on how to initialize a 3D array:

Syntax: 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}

},

};

Example program: C program to read and write 3-D array elements.

#include <stdio.h>
void main()
{
// this array can store 12 elements

int i, j, k, test[2][3][2];
printf("Enter 12 values: \n");

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


{
for (j = 0; j < 3; ++j)
{
for(k = 0; k < 2; ++k )
{
scanf("%d", &test[i][j][k]);
}
}
}

// Displaying values with proper index.

printf("\nDisplaying values:\n");

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


{
for (j = 0; j < 3; ++j)
{
for(k = 0; k < 2; ++k )
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}

getch();
}

STRINGS:

Definition: A group of characters (except double quotes sign) defined between double
quotations marks is a string.

Ex:- “my name is Mahesh”.

 If you want to include double quotes in the string to be printed, then we may use it with a
back slash as shown below.

printf(“\”my name is Mahesh”\”);

O/P: “my name is Mahesh”.

Declaration:-

C language does not support strings as a data type. So, in order to represent strings in C we use
character arrays.

Syntax: char string name [size];

Ex: char city [10];

char name[15];
Initialization: While the compiler assigns a character string to characters, the compiler
automatically supplies a null character (‘\0’) at the end of the string. So, the size of the array
should be equal to the maximum number of characters in the string plus one.

Ex: char city [9]= “NEW YORK”;

Char city [9]= {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};

When we initialize character array by listing its elements, we must supply the null character
externally.

 While initializing the character array there is no need to mention the size of the array, if
we fully initialize the array as follows.
char string[]={‘G’,’O’,’O’,’D’,’\0’};
So, the size of the array is 5.
 The default values of character array is null character (‘\0').
char string[10]=”GOOD”;
0 1 2 3 4 5 6 7 8 9
G O O D \0 \0 \0 \0 \0 \0

 The size of the character array should be greater than or equal to number of characters in
the string.
char string[3]=”GOOD”; COMILE TIME ERROR

Reading stings from the terminal:

In order to read the strings from the terminal we have 3 library functions. Those are

 scanf(). getchar(). gets().

scanf(): The input function scanf() can be used with %s as format specification to read a string
of characters.

Syntax: scanf(“%s”,string name);

Ex: char s1[15];


scanf(“%s”,s1);
The problem with the scanf() function is that it terminates its input on the first white space it
finds. A white space includes blanks, tabs etc..,

getchar(): To read a single character from the terminal we use getchar() function. This function
reads character by character until new line(\n) character is entered.

Syntax: getchar();
Ex: char c;
C=getchar();
gets(): To read a string of text containing white spaces we will use the library function as gets()
which was available in <stdio.h> header file.
Syntax: gets(string name);
Ex: char s1[15];
gets(s1);
Writing strings to screen:

In order to write the strings to screen we have 3 library functions. Those are

 printf(). putchar(). puts().

printf(): The output function printf() can be used with %s as format specification to write the
string of characters.

Syntax: printf(“%s”,string name);

Ex: char s1[15];


printf(“%s”,s1);

putchar(): To write a single character to the screen we use putchar() function.

Syntax: putchar(character name);


Ex: char c;
putchar(c);
puts(): To write a string of text containing white spaces we will use the library function as puts()
which was available in <stdio.h> header file.
Syntax: puts(string name);
Ex: char s1[15];
puts(s1);

Arithmetic operations on characters:

 C Programming Allows us to Manipulate on String.


 Whenever the Character is variable is used in the expression then it is automatically
Converted into Integer Value called ASCII value.
 All Characters can be Manipulated with that Integer Value.(Addition, Subtraction)

Examples:

1. ASCII value of : ‘a’ is 97

2. ASCII value of : ‘z’ is 121

Possible Ways of Manipulation:

Way 1: Displays ASCII value[ Note that %d in Printf ]

char x = 'a';
printf("%d",x); // Display Result = 97
Way 2 : Displays Character value[ Note that %c in Printf ]

char x = 'a';
printf("%c",x); // Display Result = a

Way 3 : Displays Next ASCII value[ Note that %d in Printf ]

char x = 'a' + 1 ;
printf("%d",x);
// Display Result = 98 ( ascii of 'b' )

Way 4 Displays Next Character value[Note that %c in Printf ]

char x = 'a' + 1;
printf ("%c",x); // Display Result = 'b'

Way 5: Displays Difference between 2 ASCII in Integer[Note %d in Printf ]

char x = 'z' - 'a';


printf ("%d",x);
/* Display Result = 25
(Difference between ASCII of z and a ) */

Way 6 : Displays Difference between 2 ASCII in Char [Note that %c in Printf ]

char x = 'z' - 'a';


printf("%c",x);
/* Display Result = ↓
(Difference between ASCII of z and a ) */

String Handling Functions

Function Work of Function

strlen() Calculates the length of string

strcpy() Copies a string to another string

strcat() Concatenates(joins) two strings


Function Work of Function

strcmp() Compares two string

strlwr() Converts string to lowercase

strupr() Converts string to uppercase

strrev() Reverses the given string

strlen ( ) :

 strlen() function calculates the length of string. It takes only one argument, i.e, string name.
 Syntax of strlen()
temp_variable = strlen(string_name);
 Function strlen() returns the value of type integer.

Program:
/* String Length using Strlen() function */
#include <stdio.h>
#include <string.h>
void main()
{
char c[20];
printf("Enter string: ");
gets(c);
//calculates the length of string before null charcter.
printf("Length of string c=%d \n",strlen(c));
getch();
}
Output :
Enter string: String
Length of string c=6
strcpy( ) :
 Function strcpy() copies the content of one string to the another string. It takes two
arguments.
 Syntax of strcpy()
strcpy( destination, source );
 Here, source and destination are both the name of the string. This statement, copies the
content of string source to the content of string destination.

Program :
#include <stdio.h>
#include <string.h>
void main()
{
char a[10],b[10];
printf("Enter string: ");
gets(a);
strcpy(b,a); //Content of string a is copied to string b.
printf("Copied string: ");
puts(b);
getch();
}
Output :
Enter string: Programming Tutorial
Copied string: Programming Tutorial
strcat( ):
 strcat() concatenates(joins) two strings. It takes two arguments, i.e, two strings and resultant
string is stored in the first string specified in the argument.
 Syntax of strcat()
strcat( first_string , second_string );
Program :
#include <stdio.h>
#include <string.h>
void main()
{
char str1[20], str2[20];
printf(“Enter the string1:”);
gets(str1);
printf(“Enter the string2:”);
gets(str2);
strcat(str1,str2);
//concatenates str1 and str2 and resultant string is stored in str1.
printf(“Concatenated String is:”);
puts(str1);
getch();
}

Output :

Enter the string1 : Welcome to


Enter the string2 : C Programming
Concatenated String is : Welcome to C Programming

stcmp( ):
 strcmp() compares two string and returns value 0, if the two strings are equal. Function
strcmp() takes two arguments, i.e, name of two string to compare.
 If two strings are not equal, strcmp() returns positive value if ASCII value of first
mismatching element of first string is greater than that of second string and negative value if
ASCII value of first mismatching element of first string is less than that of second string
 Syntax of strcmp()
temp_varaible = strcmp( string1, string2 );

Program :
#include <stdio.h>
#include <string.h>
void main()
{
char str1[30], str2[30];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Both strings are equal");
else
printf("Strings are unequal");
getch();
}
Output :

Enter first string: Apple


Enter second string: Apple
Both strings are equal.

strlwr( ):
 strlwr() function converts all the uppercase characters in that string to lowercase characters.
The resultant from strlwr() is stored in the same string.
 Syntax of strlwr()
strlwr ( string_name );
Program :
#include <stdio.h>
#include <string.h>
void main()
{
char str1[ ]="LOWer Case";
puts(strlwr(str1)); //converts to lowercase and displays it.
getch();
}
Output :
lower case
strupr( ):
 strupr() function converts all the lowercase characters in that string to uppercase
characters. The resultant from strupr() is stored in the same string.
 Syntax of strupr()
strupr ( string_name );
Program :
#include <stdio.h>
#include <string.h>
void main()
{
char str1[]="UppEr Case";
puts(strupr(str1)); //Converts to uppercase and displays it.
getch();
}
Output :
UPPER CASE
Strrev ():
 strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is given
below.
char *strrev(char *string);
 strrev( ) function is non standard function which may not available in standard library in C.

EXAMPLE PROGRAM FOR STRREV() FUNCTION IN C:


In below program, string “Hello” is reversed using strrev( ) function and output is displayed as
“olleH”.

Program :

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

int main()
{
char name[30] = "Hello";

printf("String before strrev( ) : %s\n",name);

printf("String after strrev( ) : %s",strrev(name));

return 0;
}
OUTPUT:
Stringbeforestrrev():Hello
String after strrev( ): olleH

Unit-II programs:
1. Design an algorithm to check whether the given string is palindrome or not. Translate it
into source code.
/* String Palindrome*/
#include <stdio.h>
#include <string.h>
void main()
{
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string:");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++)
{
if(string1[i] != string1[length-i-1])
{
flag = 1;
break;
}
}
if (flag==1)
{
printf("%s is not a palindrome", string1);
}
else
{
printf("%s is a palindrome", string1);
}
getch();
}
Output:
Enter a string: MALAYALAM
MALAYALAM is a palindrome

2. Write a program to concatenate the given two strings.


#include <stdio.h>
void main()
{
char s1[100], s2[100], i, j;

printf("Enter first string: ");


scanf("%s",s1);

printf("Enter second string: ");


scanf("%s",s2);

i = strlen(s1); /* i contains length of string s1. */

for(j=0; s2[j]!='\0'; ++j)


{
s1[i]=s2[j];
i++;
}
s1[i]='\0';

printf("After concatenation: %s",s1);


getch();
}
Output :
Enter first string: hello
Enter second string: hi
After concatenation: hellohi
3. Write a C program to accept 'N' numbers as input and find out the largest and the
smallest element in the list of array elements.
#include<stdio.h>
void main()
{
int a[30], i, num, smallest, largest;
printf("\n Enter no of elements :");
scanf("%d", &num);
//Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
//Consider first element as smallest and largest
smallest = largest=a[0];
for (i = 0; i < num; i++)
{
if (a[i] < smallest)
{
smallest = a[i];
}
}
for (i = 0; i < num; i++)
{
if (a[i] > largest)
{
larghest = a[i];
}
}

// Print out the Result


printf("\nSmallest Element : %d", smallest);
printf("\nLargest Element : %d", largest);
getch();
}
4. Construct a program to sort the elements of an integer array.

#include <stdio.h>
void main()
{
int arr[100];
int size, i, j, temp;
printf("Enter size of array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
if(arr[j] < arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

printf("\nElements of array in sorted ascending order: ");


for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}

getch();
}

5. Write a C program to read a string and convert uppercase characters to lowercase


characters and vice-versa.
#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
int i;
printf("Enter any string->");
scanf("%s",str);
printf("The string is->%s",str);
for(i=0;str[i]!=’\0’;i++)
{
if(str[i]>=65&&str[i]<=90)
str[i]=str[i]+32;
else
str[i]=str[i]-32;
}

printf("\nThe string in lower case is->%s",str);


getch();
}

6.Write a program to perform the addition and subtraction of two matrices using two-
dimensional arrays with necessary conditions.
Refer class notes.
7.Write program to perform the matrix multiplication of two MxN matrices.
Refer class notes.

8. Write a program to find the sum of given ‘n’ numbers using arrays.

#include <stdio.h>
void main()
{
int n, sum = 0, i, a[20];
printf("Enter the number of integers you want to add\n");
scanf("%d", &n);
printf("Enter %d integers\n",n);

for (i = 0; i< n; i++)


{
scanf("%d", &a[i]);
}
for (i = 0; i< n; i++)
{
sum = sum + a[i];
}
printf("Sum of entered integers = %d\n",sum);
getch();
}

9. Construct a program to find the sum and average of given ‘n’ floating point numbers
using arrays.

#include <stdio.h>
void main()
{
int n, i;
float a[20], sum = 0,average;

printf("Enter the number of integers you want to add\n");


scanf("%d", &n);

printf("Enter %d integers\n",n);

for (i = 0; i< n; i++)


{
scanf("%f", &a[i]);
}
for (i = 0; i< n; i++)
{
sum = sum + a[i];
}
average=sum/n;
printf("Sum of entered integers = %f\n",sum);
printf("Average of entered integers = %f\n",average);
getch();
}
10. Construct a program to sort the names of employees alphabetically.
#include <stdio.h>
#include <string.h>
void main()
{
char name[10][8], temp[8];
int i, j, n;
printf("Enter the value of n \n");
scanf("%d", &n);
printf("Enter %d names n", \n);
for (i = 0; i < n; i++)
{
scanf("%s", name[i]);
}
for (i = 0; i < n ; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf("Sorted names are\n");
for (i = 0; i < n; i++)
{
printf("%s\n",name[i]);
}
getch();
}

11. Write a program to count number of vowels, number of digits and number of other symbols in a
given line of text.

void main()
{
char line[150];
int i, vowels, digits, symbols,consonents;
vowels = digits = symbols = consonents=0;
printf("Enter a line of string: ");
scanf("%s", line);

for(i=0; line[i]!='\0'; i++)


{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
line[i]=='o' || line[i]=='u' || line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' ||
line[i]=='U')
{
vowels++;
}
else if(line[i]>='0' && line[i]<='9')
{
digits++;
}
else if((line[i]>='a'&&line[i]<='z')||(line[i]>='A'&&line[i]<='Z'))
{
consonents++;
}
else
symbols++;
}

printf("Vowels: %d",vowels);
printf("\nDigits: %d",digits);
printf("\nSpecial Symbols: %d", symbols);
printf("\nConsonents: %d",consonents);
getch();
}

12. Write a program to transpose the given 3x3 matrix.


#include <stdio.h>
void main()
{
int a[10][10], transpose[10][10],i, j;
printf("\nEnter elements of matrix:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("Enter element a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}
}

printf("\nEntered Matrix: \n");


for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
transpose[j][i] = a[i][j];
}
}

printf("\nTranspose of Matrix:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%d ",transpose[i][j]);

}
printf("\n\n");
}

getch();
}
13. Write a program to print the characters of a string in reverse order.
#include<stdio.h >
#include<conio.h>
#include<string.h>
void main()
{
char st[20],ch;
int i,l;
clrscr();
printf("Enter the string :-> ");
gets(st);
l=strlen(st);
printf("Original String :-> %s\n",st);
for(i=0;i<l/2;i++)
{
ch=st[i];
st[i]= st[l-1-i];
st[l-1-i]=ch;
}
printf("Reverse String is :-> %s\n",st);
getch();
}

14. Write a C program to print given integer array in reverse order


void main()
{
int arr[30], i, j, num, temp;
printf("\nEnter no of elements : ");
scanf("%d", &num);
printf("\n Enter the array elements : ");
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
j = i - 1;
i = 0;
while (i < j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
printf("\nResult after reversal : ");
for (i = 0; i < num; i++)
{
printf("%d \t", arr[i]);
}
getch();
}

15. Write a C program to display the length of a string without using any string handling function.
#include <stdio.h>
void main()
{
char s[1000], count=0,i;
printf("Enter a string: ");
scanf("%s", s);
for(i = 0; s[i] != '\0'; i++)
{
count++;
}
printf("Length of string: %d",count);
getch();
}

16. Write a C program to read a 3x3 matrix and find the sum of diagonal elements.

#include<stdio.h>
void main()
{
int a[10][10],i,j,sum=0,m,n;
printf("\nEnter the row and column of matrix: ");
scanf("%d %d",&m,&n);
printf("\nEnter the elements of matrix: ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nThe matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<m;j++)
{
printf("%d\t",a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
sum=sum+a[i][j];
}
}
printf("\n\nSum of the diagonal elements of a matrix is: %d",sum);
getch();
}

17. Write a C program to generate 2x2 Identity Matrix.


#include<stdio.h>
void main()
{
int a[10][10];
printf("\nThe 2X2 Identity matrix is\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
if(i==j)
a[i][j]=1;
else
a[i][j]=0;
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}
getch();
}

18. Write a program to merge two integer arrays into third array. And sort the third array and
display them.

#include<stdio.h>
void main()
{
int a[10],m,b[10],n,c[10],i,j,k=0;
clrscr();
printf("enter the number of elements of array A\n");
scanf("%d",&m);
printf("enter the number of elements of array B\n");
scanf("%d",&n);
printf("enter the elements of array A\n");
for(i=0;i<m;i++)
{
scanf("%d",&a[i]);
}
printf("enter the elements of array B\n");
for(j=0;j<n;j++)
{
scanf("%d",&b[j]);
}
for(i=0;i<m;i++)
{
c[k]=a[i];
k++;
}
for(j=0;j<m+n;j++)
{
c[k]=b[j];
k++;
}
for(i=0;i<m+n;i++)
{
for(j=i+1;j<m+n;j++)
{
int temp;
if(c[i]>c[j])
{
temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}
}
printf("The list after sorting is\n");
for(i=0;i<m+n;i++)
printf("%d\t",c[i]);
getch();
}

You might also like