Unit 2 PC Notes
Unit 2 PC Notes
Where, data_type: e.g int, char, float. . .array_name it is a valid variable name
size is the Number of elements the array
Example : int r[7];
int r[7];
r[0] r[1 r[2] r[3] r[4] r[5] r[6]
ARRAY INITIALIZATION
The values can be initialized to an array when they are declared like ordinaryvariables, otherwise
they holdgarbage values.
SYNTAX: data_type array_name[size]={list of values};
Types of array :
1. One Dimensional array
2. Two Dimensional array
3. Multi Dimensional array
Programming in C 1
2.2 ONE DIMENSIONAL ARRAY
An array with a single subscript is called One Dimensional array. A One-Dimensional Array is
also known as 1D Array
It occupies continuous memory location.
DECLARATION AND INITIALIZATION OF 1D ARRAY
Declaration of 1 D Array :
Syntax: datatype variable_name[size];
Eg : int a[5];
Initialising a 2D array
To create a 2D array of integers, take a look at the following example: int
matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
The first dimension represents the number of rows [2], while the second dimensionrepresents the
number of columns [3]. The values are placed in row-order, and canbe visualized like this:
Column 1 Column 1 Column 1
Row 1 1 4 2
Row 2 3 6 8
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
To change the value of an element, refer to the index number of the element in each ofthe dimensions:
The following example will change the value of the element in the first row (0) and firstcolumn (0):
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;
printf("%d", matrix[0][0]); // Now outputs 9 instead of 1
Programming in C 3
Reading, Storing and accessing elements of a 2-D array(Loop
through a 2D Array)
The elements of a 2D array can be read and stored using nested loops. To loop through a multi-
dimensional array, you need one loop for each of the array's dimensions. The following example gets
and prints all elements in the matrix or 2 D array
Example
// 2 D array Output :
#include <stdio.h>
void main() 1234
{ 1 2
int x[2][2],i,j; 3 4
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&x[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",x[i][j]);
}
printf(“\n”);
}
}
MULTI – DIMENSIONAL ARRAY
If the dimension are three or more , they are called as multidimensional array. ieArrays with
more than 3 or more subscripts are caller Multi dimensional arrays
Multidimensional arrays are slower than the single dimensional array
ARRAY DECLARATION:
data_type array_variable[size_1][size_2] .............. [size_n];
SYNTAX:
E.g: float b[4][4][4][4];
clrscr();
printf("Elements of
an array \n");for 1 2 3
(i=0;i<3;i++) 4 5 6
{ 7 8 9
for (j=0;j<3;j++)
{ 1 4 7
for(k=0;k<3;k++) 2 5 8
{ 3 6 9
printf("%d\t",a[i][j][k]);
} 1 4 4
printf("\n"); 2 4 7
} 6 6 3
printf("\n");
}
getch();
}
Advantages of an Array
Allow random access of elements
Capable of storing many elements at a time
The direct indexing supported by array is their biggest advantage. Direct indexing
the time required to access any element in an array
Limitations of arrays:
The memory to an array is allocated at the compile time
Arrays are static in nature. The size of an array can’t be expanded or can’tbe changed at the
runtime.
The size of an array has to be kept big enough to accommodate the worstcases.
Therefore, memory usage in case of arrays is inefficient
2.4 STRING
String is a sequence characters enclosed within double quotes.
The string is always declared as character arrays, In other words, characterarrays are
called as strings.
NULL (‘\0’ ) character is used at the end of the string.
Ex : 1. “God Bless!!”
2. “A”
3. “ ”
char edu[ ]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,’\0’};
Programming in C 5
DISPLAY OF STRING WITH DIFFERENT FORMATS
The printf() function with %s format specifier is used to display the string on thescreen.
Variousformats is shown below
Example ; char a[15]="STRINGHANDLING";
STRING ARRAY
A string is a collection of characters. A string constant is a one dimensionalarray
ofcharacters terminated by a null („\0‟) character.
Example: char name[] = {‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’,’\0’};
Terminating the string with null „\0‟ is important, because it is the only waythe
functions that work with a string can know where the string ends.
The last character is called ‘\0’ null character, it occupies one byte memoryand the last
character is always
Example: char name[]=”COMPUTER”;
C O M P U T E R \0
Example: Program to read and print the character string from the array
#include<stdio.h>
void main()
{
char str[20]; 17
printf(“Enter string:\n”);
scanf(“%s”,str);
printf(“String is:%s”,str);
}
Programming in C 6
The commonly used C string library functions are given in following table
S.NO FUNCTION SYNTAX PURPOSE
1. strlen() var = strlen(string); To calculate length of the
string.
2. strcpy() strcpy(string1,string2); To copy string2 in to string1.
3 strncpy() strncpy(str1,str2); To copy n characters of a str2into
str1
4 strcat() strcat(string1,string2); To combine two strings
5 strncat() strncat(string1,string2); To concatenate a portion of
one string with Another
6 strcmp() strcmp(string1,string2); To compare character of two
string
7 strncmp() strncmp(str1,str2,n); To compare a position of two
strings
8. strcmpi() strcmpi(string1,string2); To compare character of two
string without case sensitivity.
Programming in C 7
printf("\nCopy of the string is: %s",str1);
printf("\nStrcat [concatenated] is %s",name);
if(strcmp(str1,str2)==0)
{
printf("\nstring 1 and string 2 are equal");
}
else
{
printf("\nstring 1 and string 2 are not equal");
}}
Output:
Length of the name is: 9
Copy of the string is: Computer
Strcat [concatenated] is C ProgramComputerstring 1
and string 2 are equal
2 Binary Search
Binary Search is defined as a searching algorithm used in a sorted array by repeatedly
dividing the search interval in half. The idea of binary search is to use the information that the
array is sorted and reduce the time complexity.
Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target = 23.
0 1 2 3 4 5 6 7 8 9
First Step:
o Initially the search space is from 0 to 9.
o Let’s denote the boundary by L and H where L = 0 and H = 9 initially.
o Now mid of this search space is M = 4.
o So compare target with arr[M].
Second Step:
o As arr[4] is less than target, switch the search space to the right of 16, i.e.,[5, 9].
o Now L = 5, H = 9 and M becomes 7.
o Compare target with arr[M].
Third Step:
o arr[7] is greater than target.
o Shift the search space to the left of M, i.e., [5, 6].
o So, now L = 5, H = 6 and M = 6.
o Compare arr[M] with target.
o Here arr[M] and target are the same.
Programming in C 10
So, we have found the target.
Program
// binary search
#include<stdio.h>
int main()
{
int c, start, stop, mid, n, search, a[100];
printf("Enter number of elements:\n");
scanf("%d",&n);
printf("Enter %d integers:\n", n); Output :
for (c = 0; c < n; c++) Enter number of elements:
scanf("%d",&a[c]); 5
Enter 5 integers:
printf("Enter the value to find:\n");
4 6 8 10 12
scanf("%d", &search); Enter the value to find:
start = 0; 10
stop = n - 1; element found at 4
while(start<=stop)
{
mid=(start+stop)/2;
if(search==a[mid])
{ printf("element found at %d",mid+1);
break;}
else
if(search<a[mid])
stop=mid-1;
else
start=mid+1;
}
Programming in C 11
if (start > stop)
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
Comparison between Linear Search and Binary Search
1 In linear search input data need not In binary search input data need to be in
to be in sorted. sorted order.
2 It is also called sequential search. It is also called half-interval search.
1 COMPUTING MEAN
The mean (average) of a data set is found by adding all numbers in the data set and thendividing by the
number of values in the set.
#include<stdio.h>
#include<conio.h>
void main() OUTPUT
{
int a[100],n,i;
float sum=0,mean;
clrscr();
printf("enter the number of elements");
scanf("%d",&n);
printf("enter the elements one by one");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0; i<n; i++)
sum=sum+a[i];
mean=sum/n;
printf("the mean of given array number is %f",mean);getch();
}
2. COMPUTING MEDIAN
The median is the middle value when a data set is ordered from least to greatest.
#include<stdio.h>
void main( )
{
int i,j,n,a[10],t;
float median;
clrscr();
printf("Enter the number of items\n");
scanf("%d", &n); /* Reading items into array a */
Programming in C 12
printf("Input %d values \n",n);
for (i = 0; i < n ; i++)
scanf("%d", &a[i]);
/* Sorting begins */
for (i = 0 ; i < n ; i++)
{
for (j = i+1 ; j <n ; j++)
{
if (a[i] > a[j])
{
t = a[j];
a[j] = a[i];
a[i] = t;
}
}
}
for (i = 0 ; i <n ; i++)
printf("%d ", a[i]);
/* calculation of median */
if ( n % 2 == 0)
median = (a[n/2] + a[(n-1)/2])/2.0 ;
else
median = a[(n-1)/2];
/* Printing */
printf("\n\nMedian is %f\n", median);
getch();
}
OUTPUT
3. COMPUTING MODE
The mode is the number that occurs most often in a data set.
#include<stdio.h>
void main()
{
int maxValue = 0, maxCount = 0, i, j,n=5,a[10];
clrscr();
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for (i = 0; i < n; ++i)
{
int count = 0;
for (j = 0; j < n; ++j)
{
if (a[j] == a[i])
Programming in C 13
++count;
}
if (count > maxCount)
{
maxCount = count;
maxValue = a[i];
}
}
printf("Mode = %d ", maxValue);
getch();
}
OUTPUT
1. MATRIX ADDITION
#include <stdio.h>int
main()
{
int rowCount, columnCount, i, j;
int firstMatrix[10][10], secondMatrix[10][10], resultMatrix[10][10];
printf("Number of rows of matrices to be added : ");
scanf("%d", &rowCount);
printf("Number of columns matrices to be added : ");
scanf("%d", &columnCount);
printf("Elements of first matrix : \n");
for (i = 0; i < rowCount; i++)
for (j = 0; j < columnCount; j++)
scanf("%d", &firstMatrix[i][j]);
printf("Elements of second matrix : \n");
for (i = 0; i < rowCount; i++)
for (j = 0; j < columnCount; j++)
scanf("%d", &secondMatrix[i][j]);
printf("Sum of entered matrices : \n");
for (i = 0; i < rowCount; i++)
{
for (j = 0; j < columnCount; j++)
{
resultMatrix[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
Programming in C 14
printf("%d\t",resultMatrix[i][j]);
}
printf("\n");
}
return 0;}
OUTPUT
Number of rows of matrices to be added : 2
Number of columns matrices to be added : 2
Elements of first matrix :
5
5
5
5
Elements of second matrix :11
1
1
Sum of entered matrices :6 6
6 6
2. MATRIX DETERMINANT
#include<stdio.h>int
main()
{
int a[3][3], i, j;
long determinant;
printf("Enter the 9 elements of matrix: ");
for(i = 0 ;i < 3;i++)
for(j = 0;j < 3;j++)
scanf("%d", &a[i][j]);
Programming in C 15
3. MATRIX TRANSPOSE
#include <stdio.h>
void main() OUTPUT:
{
static int array[10][10];
int i, j, m, n;
printf("Enter the order of the matrix \n");
scanf("%d %d", &m, &n);
printf("Enter the coefiicients of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");}
printf("Transpose of matrix is \n");
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
}
3 MATRIX SCALING
#include <stdio.h>
void main()
{
int a[3][3],num,i,j;
printf(“ENTER A 3*3 Matrix\n”);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter any number to multiply with matrix A: ");
scanf("%d", &num);
for(i=0; i<3; i++)
{ output :
for(j=0; j<3; j++)
16
{
a[i][j] = num * a[i][j];
}
}
printf("\nResultant matrix c.A = \n");
for(i=0; i<3; i++)
{
for(j=0; j<3;j++)
{
printf("%d",a[i][j]);
}
printf("\n");
}
}
Sample Output:
Enter array size: 5
Enter array elements: 6 2 2 7 9
Resultant Array:
6279
Sample Output:
Enter a string : Hello
Enter the character to be searched : l
Occurrence of character is 2
#include<stdio.h>
#include<conio.h>
void main()
{
char line[150];int
i,v,c,d,s;
v=c=d=s=0;
printf("Enter a line of string:\n");
gets(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') v=v+1;
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))c=c+1;
else if(line[i]>='0'&&c<='9')
d=d+1;
else if (line[i]==' ')
s=s+1;
}
printf("Vowels: %d",v);
printf("\nConsonants: %d",c);
printf("\nDigits: %d",d); printf("\nWhite spaces: %d",s);getch();
}
Sample output: Enter a
line of string :god is
love1
Vowels: 4
Consonants: 5
Digits:1
White spaces: 2
7. To concatenate two strings without using library function
void main(void)
{
char str1[25],str2[25];int
i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
25
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}
Output:
Enter First String:HELLO
Enter Second String:GIRL
Concatenated String is HELLOGIRL
Output:
The Strings are equal
Output:
String s2: computer
Output : Enter
String : gel
Reverse string leg
27
12. Is address operator used in scanf() statement to read an array? Why?
13. What is the role of strrev()?
14. Discover the meaning of a String.
15. How to initialize a string? Give an example.
16. Differentiate between Linear search and Binary search.
17. Specify any two methods of sorting.
18. Design a C program for compare any two string
19. Sort the following elements using selection sort method 23, 55, 16, 78, 2
20. List out the any four functions that are performed on character strings.
21. Given an array int a [10] = {101, 012, 103, 104, 105, 106, 107, 108, 109, 110}. Show thememory
representation and calculate its length.
22. Name any two library functions used for string handling.
Write the output of the following Code:
main()
{
static char name[ ]="Engineering” int
23. i=0;
while (name[i]!='\0')
{
printf("%c" name[i]);
i++;
}
}
24. Define an array? How do you initialize array
25. How do you assign an array to another array
Part B
Explain the need for array variables. Describe following with respect to arrays:
1. Declaration of array
Accessing an array element.
2. Write a C program to re-order a one-dimensional array of numbers in descending order.
3. Write a C program to multiply two matrices (2D array) by getting input from the user.
Write a C program to perform the following matrix operations:
4. Addition
Subtraction
Scaling
5. Write the C program to median and mode for an array of numbers and explain.
6. Write a C program to calculate mean, median and mode for an array of elements.
7. Write a C program for Determinant and transpose of a matrix.
Describe the following with suitable examples.
8. Initializing a 2 Dimensional Array
Memory Map of a Dimensional Array.
9. Explain about the String Arrays and its manipulation in detail.
28
10. Write a C program to find average marks obtained by a 30 students in a test.
11. What are the different types of string functions? Describe with their purpose.
12. Write short notes on Reading and Writing string.
13. Write a C program to sort the n numbers using selection sort.
14. Develop a C program to search an element from the array.
15. Differentiate binary search from linear search.
16. Write a C program to find whether the given string is palindrome or not without using
string functions.
Describe the following functions with examples.
strlen()
17. strcpy()
strcat()
strcmp()
18. Write the C program to find the number of Vowels, Consonants, Digits and white spacein a
string.
19. Write a C program to count the number of characters, spaces, vowels, constants andothers
using string functions.
Discuss about the following --
20. Advantages and disadvantages of linear and binary search.
Discuss briefly runtime initialization of a two dimensional array.
Explain about the following:
21. String and character array.
Initializing string variables.
String input and output.
22. Explain binary search procedure. Write a C program to perform binary search andexplain.
23. Write a C Program to take 5 values from the user and store them in a array
29