Unit-2 C-Language
Unit-2 C-Language
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.
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.
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].
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.
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 initialization of array elements is same as ordinary variable initialization. The
general form of initialization of array is,
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
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();
}
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 −
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 */
}
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
#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
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:
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
0 1 2 3
20 35 45 90
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. 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.
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
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
Array is used to store the number of elements belonging to same data type.
int arr[30];
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.
int roll[5];
So we are using array which can store multiple values and we have to remember just single
variable name.
We can store elements to be sorted in an array and then by using different sorting technique we
can sort the elements.
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Bucket Sort
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]
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.
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}
};
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'.
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 −
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 −
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 () {
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
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.
type array_name[d1][d2][d3][d4]………[dn];
Examples:
1. int table[5][5][20];
2. float arr[5][6][5][6][5];
In Example 1:
In Example 2:
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.
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.
},
},
},
};
#include <stdio.h>
void main()
{
// this array can store 12 elements
int i, j, k, test[2][3][2];
printf("Enter 12 values: \n");
printf("\nDisplaying values:\n");
getch();
}
STRINGS:
Definition: A group of characters (except double quotes sign) defined between double
quotations marks is a string.
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.
Declaration:-
C language does not support strings as a data type. So, in order to represent strings in C we use
character arrays.
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.
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
In order to read the strings from the terminal we have 3 library functions. Those are
scanf(): The input function scanf() can be used with %s as format specification to read a string
of characters.
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(): The output function printf() can be used with %s as format specification to write the
string of characters.
Examples:
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
char x = 'a' + 1 ;
printf("%d",x);
// Display Result = 98 ( ascii of 'b' )
char x = 'a' + 1;
printf ("%c",x); // Display Result = 'b'
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 :
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 :
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.
Program :
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = "Hello";
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
#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;
}
}
}
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);
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 %d integers\n",n);
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);
printf("Vowels: %d",vowels);
printf("\nDigits: %d",digits);
printf("\nSpecial Symbols: %d", symbols);
printf("\nConsonents: %d",consonents);
getch();
}
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();
}
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();
}
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();
}