3.1 Arrays - Introduction:: Unit Iii - Arrays and Strings

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

Unit-III GE6151- COMPUTER PROGRAMMING

UNIT III - ARRAYS AND STRINGS


Arrays – Initialization – Declaration – One dimensional and Two dimensional
arrays. String- String operations – String Arrays. Simple programs- sorting-
searching – matrix operations.
3.1 ARRAYS - INTRODUCTION:
 An array is a collection of data items, all of the same type, accessed using a common name.
 So far we were using the single variable name for storing one data item. If we need to store
the multiple copies of the same data then it is very difficult for the user.
Example of Array
 Suppose we have to store the roll numbers of the 100 students the we have to declare 100
variables named as roll1,roll2,roll3,…….roll100 which is very difficult job.
 Arrays solve this problem; all Elements are stored in the Contiguous memory
 All elements in the array are accessed using the subscript variable.

The above array is declared as int a[5];


a[0] = 4;
a[1] = 5;
a[2] = 33;
a[3] = 13;
a[4] = 1;
 4,5,33,13,1 are actual data items, 0,1,2,3,4 are index variables

3.2 ARRAY DECLARATION


 A programmer need to specify the type of the elements and the number of elements required
by an array.
 Array has to be declared before using it in C Program.
Syntax:
data_type array_name [size];

S.KAVITHA / AP / CSE / MSAJCE Page 1 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Syntax Explanation

Data Type Data Type specifies the type of the array. We can compute the size required for
storing the single cell of array.
Array_name Name given to the array. Using this identifier name array can be accessed.

Size of Array It is maximum size that array can have.

Examples:
// Array of 10 integer roll numbers
int roll[10]
In the above example we are declaring the integer array of size 10. Array is single dimensional
and have 10 elements starting from roll[0],roll[1].....roll[9]
INDEX OR SUBSCRIPT VARIABLE:
 Individual data items can be accessed by the name of the array and an integer enclosed in
square bracket called subscript variable / index
 Subscript Variables helps us to identify the item number to be accessed in the contiguous
memory.
APPLICATION OF ARRAY :
Below are the some of the applications of array
1. Stores Elements of Same Data Type
2. Array Used for Maintaining multiple variable names using single name
3. Array Can be Used for Sorting Elements
4. Array Can Perform Matrix Operation
5. Array Can be Used in CPU Scheduling
 CPU Scheduling is generally managed by Queue. Queue can be managed and
implemented using the array.
6. 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 retrieve when
control comes back. This is similar operation like stack.

S.KAVITHA / AP / CSE / MSAJCE Page 2 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

LIMITATIONS OF ARRAY:
1. Static Data
 Array is Static data Structure, Memory Allocated during Compile time.
 Once Memory is allocated at Compile Time it Cannot be Changed duringRun-time
2. Can hold data belonging to same Data types
 Elements belonging to different data types cannot be stored in array
3. Inserting data in Array is Difficult
 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.
 This operation is faster if the array size is smaller, but same operation will take more
time when array is larger in size.
4. Deletion Operation is difficult
 After deletion empty space will be created and thus we need to fill the space by
moving elements up in the array.
5. Bound Checking
 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.
6. Shortage of Memory
 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.
7. Wastage of Memory
 Wastage of Memory , if array of large size is defined

3.3 ARRAY TYPES


1.Single Dimensional Array :
2. Multi Dimensional Array :

3.3.1 SINGLE DIMENSIONAL ARRAY :


 Array having only one subscript variable is called One-Dimensional array
 It is also called as Single Dimensional Array or Linear Array

S.KAVITHA / AP / CSE / MSAJCE Page 3 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Syntax :
data-type array_name [size];
Example:
int iarr[3] = {2, 3, 4};
char carr[20] = "c4learn" ;
float farr[3] = {12.5,13.5,14.5} ;

INITIALIZING 1-D ARRAY


Different Methods of Initializing 1-D Array
Initializing 1-D Array is called as compiler time initialization if and only if we assign certain set
of values to array element before executing program. i.e at compilation time.

Initializing 1-D
array

Compile time Run time


initialization initialization

Specifying size Without


specifying size

Compile time initialization:


 Size is Specified Directly
 Size is Specified Indirectly
Array Size Specified Directly
 In this method , we specify the Array Size directly.
Eg: int num[5] = {2,8,7,6,0};
 In the above example we have specified the size of array as 5 directly in the initialization
statement. Compiler will assign the set of values to particular element of the array.
Size Specified Indirectly
 In this scheme, we does not provide size to an array but instead we provide set of values
to the array.

S.KAVITHA / AP / CSE / MSAJCE Page 4 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Eg: int num[] = {2,8,7,6,0};


 Here, compiler Counts the Number Of Elements Written Inside Pair of Braces and
Determines the Size of An Array.
 After counting the number of elements inside the braces, The size of array is considered
as 5 during complete execution.
 This type of Initialization Scheme is also Called as “Compile Time Initialization“

int numbers[2000]={245};
 The above example sets the first value of the array to 245, and the rest to 0.

Sample Program
#include <stdio.h>
void main()
{
int num[] = {2,8,7,6,0};
int i;
for(i=0;i<5;i++) {
printf("\nArray Element num[%d] : %d",i+1,num[i]);
}
}
Output :
Array Element num[1] : 2
Array Element num[2] : 8
Array Element num[3] : 7
Array Element num[4] : 6
Array Element num[5] : 0

S.KAVITHA / AP / CSE / MSAJCE Page 5 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

3.3.2 MULTI DIMENSIONAL ARRAY:


 Array having more than one subscript variable is called Multi-Dimensional array.
 Multi Dimensional Array is also called as Matrix.
Syntax :
data-type array_name[row_subscript][column-subscript];
Example :
int a[3][3] = { 1,2,3
5,6,7
8,9,0 };

Consider the Two dimensional array –


 Two Dimensional Array requires Two Subscript Variables
 Two Dimensional Array stores the values in the form of matrix.
 First Subscript Variable denotes the “Row” of a matrix.
 Second Subscript Variable denotes the “Column” of a matrix.

DECLARATION AND USE OF TWO DIMENSIONAL ARRAY :


int a[3][4];
Use :
for(i=0;i<row,i++)
for(j=0;j<col,j++)
{
printf("%d",a[i][j]);
}

S.KAVITHA / AP / CSE / MSAJCE Page 6 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

INITIALIZING 2D ARRAY
We have divided the concept into three different types –

Method 1 : Initializing all Elements rowwise


For initializing 2D Array we need to assign values to each element of an array using the below
syntax.
int a[3][2] = {
{ 1 , 4 },
{ 5 , 2 },
{6,5}
};
Consider the below program –
#include<stdio.h>
int main() {
int i, j;
int a[3][2] = { { 1, 4 },
{ 5, 2 },
{ 6, 5 }};
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}

S.KAVITHA / AP / CSE / MSAJCE Page 7 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

OUTPUT :
14
52
65
We have declared an array of size 3 X 2, It contain overall 6 elements.
Row 1 : { 1 , 4 },
Row 2 : { 5 , 2 },
Row 3 : { 6 , 5 }
We have initialized each row independently
a[0][0] = 1
a[0][1] = 4
Method 2 : Combine and Initializing 2D Array
Initialize all Array elements but initialization is much straight forward. All values are assigned
sequentially and row-wise
int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };
Consider the below example program –
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { 1, 4, 5, 2, 6, 5 };

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


for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Output will be same as that of above program #1

S.KAVITHA / AP / CSE / MSAJCE Page 8 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Method 3 : Some Elements could be initialized


int a[3][2] = {
{ 1 },
{ 5 , 2 },
{6}
};
In this case we have declared and initialized 2-D array like this
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { { 1 },
{ 5, 2 },
{ 6 }};

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


for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Output :
10
52
60
THINGS TO CONSIDER WHILE INITIALIZING 2D ARRAY –
 When we give values during one dimensional array declaration, it is not necessary to mention
dimension.

S.KAVITHA / AP / CSE / MSAJCE Page 9 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

 But that‟s not the case with 2D array; you must specify the second dimension even if you are
giving values during the declaration. Let‟s understand this with the help of few examples –
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }

MEANING OF TWO DIMENSIONAL ARRAY :


 Matrix is having 3 rows ( i takes value from 0 to 2 )
 Matrix is having 4 Columns ( j takes value from 0 to 3 )
 Above Matrix 3×4 matrix will have 12 blocks having 3 rows & 4 columns.
 Name of 2-D array is „a„ and each block is identified by the row & column number. Row
number and Column Number Starts from 0.

Cell Location Meaning

a[0][0] 0th Row and 0th Column

a[0][1] 0th Row and 1st Column

a[0][2] 0th Row and 2nd Column

a[0][3] 0th Row and 3rd Column

a[1][0] 1st Row and 0th Column

a[1][1] 1st Row and 1st Column

a[1][2] 1st Row and 2nd Column

a[1][3] 1st Row and 3rd Column

S.KAVITHA / AP / CSE / MSAJCE Page 10 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Cell Location Meaning

a[2][0] 2nd Row and 0th Column

a[2][1] 2nd Row and 1st Column

a[2][2] 2nd Row and 2nd Column

a[2][3] 2nd Row and 3rd Column

MEMORY REPRESENTATION
 Consider 3×3 Array is stored in Contiguous memory location which starts from 4000 .
 Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next
memory location i.e Elements stored row-wise
 After Elements of First Row are stored in appropriate memory location , elements of next
row get their corresponding memory locations.
 This is integer array so each element requires 2 bytes of memory.
Basic Memory Address Calculation :
a[0][1] = a[0][0] + Size of Data Type

Element Memory Location

a[0][0] 4000

a[0][1] 4002

a[0][2] 4004

a[1][0] 4006

a[1][1] 4008

a[1][2] 4010

a[2][0] 4012

a[2][1] 4014

S.KAVITHA / AP / CSE / MSAJCE Page 11 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

a[2][2] 4016

3.4 ACCESSING ARRAY:


Accessing One-Dimensional Array Elements
 Array elements are randomly accessed using the subscript variable.
 Array can be accessed using array-name and subscript variable written inside pair of square
brackets [].
Consider the below example of an array –

In this example we will be accessing array like this


arr[3] = Third Element of Array
arr[5] = Fifth Element of Array
arr[8] = Eighth Element of Array
For example you want to read and display array elements, you can do it just by using any loop.
Suppose array is mydata[20].
for (int i=0; i<20; i++)
{
printf("%d\n", mydata[x]);
}
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\nElement at arr[%d] is %d",i,arr[i]);
}

S.KAVITHA / AP / CSE / MSAJCE Page 12 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

}
Output :
Element at arr[0] is 51
Element at arr[1] is 32
Element at arr[2] is 43
Element at arr[3] is 24
Element at arr[4] is 5
Element at arr[5] is 26
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.
Example:
int val = a[2][3];
 The above statement will take the 4th element from the 3rd row of the array.
 Another way is using the nested loops for matrix manipulations

3.5 STRING - INTRODUCTION:


 Strings are one-dimensional array of characters terminated by a nullcharacter '\0'. Thus a
null-terminated string contains the characters that comprise the string followed by a null.
 String is the collection of characters stored at contiguous memory locations
 The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the
string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
 If you follow the rule of array initialization then you can write the above statement as follows

char greeting[] = "Hello";
 Following is the memory presentation of the above defined string
 Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array.
 String always Terminated with NULL Character („/0′)

S.KAVITHA / AP / CSE / MSAJCE Page 13 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

char name[10] = {'P','R','I','T','E','S','H','\0'}

 NULL Character is having ASCII value 0


 ASCII Value of '\0' = 0
 As String is nothing but an array , so it is Possible to Access Individual Character
name[10] = "Pritesh";
 It is possible to access individual character
name[0] = 'P';
name[1] = 'r';
name[2] = 'i';
name[3] = 't';
name[4] = 'e';
name[5] = 's';
name[6] = 'h';
name[7] = '\0';

STRING DECLARATION:
String data type is not supported in C Programming. String means Collection of Characters to
form particular word. We cannot declare string using String Data Type, instead of we use array
of type character to create String.
 Character Array is Called as „String‟.Character Array is Declared Before Using it in Program
Syntax :
char String_Variable_name [ SIZE ] ;
Examples :
char city[30];
char name[20];
 These are some sample declarations of the String.In the first example we have defined string
to store name of city.Maximum Size to store City is 30 which must be specified inside the
Square brackets.

S.KAVITHA / AP / CSE / MSAJCE Page 14 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

 Do not use String as data type because String data type is included in later languages such as
C++ / Java. C does not support String data type
String city;
 When you are using string for other purpose than accepting and printing data then you must
include following header file in your code
#include<string.h>

STRING INITIALIZATION:
 Whenever we declare a String then it will contain garbage values inside it. We have to
initialize String or Character array before using it.
 Process of Assigning some legal default data to String is Called Initialization of String. There
are different ways of initializing String in C Programming –
o Initializing Unsized Array of Character
o Initializing String Directly
Unsized Array and Character:
 Unsized Array : Array Length is not specified while initializing character array using this
approachArray length is Automatically calculated by Compiler
 Individual Characters are written inside Single Quotes , Separated by comma to form a list of
characters. Complete list is wrapped inside Pair of Curly braces
 NULL Character should be written in the list because it is ending or terminating character in
the String/Character Array
char name [] = {'P','R','I','T','E','S','H','\0'};
Directly initialize String Variable:
 In this method we are directly assigning String to variable by writing text in double quotes.
 In this type of initialization , we don‟t need to put NULL or Ending / Terminating
character at the end of string. It is appended automatically by the compiler.
char name [ ] = "PRITESH";

gets() FUNCTION:
 Reads characters from the standard input (stdin) and stores them as a C string into str until a
newline character or the end-of-file is reached.

S.KAVITHA / AP / CSE / MSAJCE Page 15 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Syntax:
gets(variable-name)
Example :
#include<stdio.h>
void main()
{
char name[20];
printf("\nEnter the Name : ");
gets(name);
}
Explanation:
 Whenever gets() statement encounters then characters entered by user (the string with spaces)
will be copied into the variable.
 If user start accepting characters , and if new line character appears then the newline
character will not be copied into the string variable
 A terminating null character is automatically appended after the characters copied to string
 gets() uses stdin (Standard Input Output) as source, but it does not include the ending newline
character in the resulting string and does not allow to specify a maximum size for string
variable
 Blank Spaces are allowed in gets() :
o When user starts typing the characters then all characters will be copied to string and
when user enters newline character then process of accepting string will be stopped.

getchar() FUNCTION:
 Accepts the String Character by Character
 Getchar() function is also one of the function which is used to accept the single character
from the user.
 The characters accepted by getchar() are buffered until RETURN is hit means getchar() does
not see the characters until the user presses return. (i.e Enter Key)
Syntax:
char ch = getchar();

S.KAVITHA / AP / CSE / MSAJCE Page 16 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

 When control is on above line then getchar() function will accept the single character. After
accepting character control remains on the same line.
 When user presses the enter key then getchar() function will read the character and that
character is assigned to the variable „ch‟.

puts() FUNCTION:
Way 1 :Messaging
puts(" Type your Message / Instruction ");
 puts() can be used to display message.
Way 2 : Display String
puts(string_Variable_name) ;
 puts is included in header file “stdio.h”
 As name suggest it used for Printing or Displaying Messages or Instructions
Example :
#include< stdio.h>
#include< conio.h>
void main()
{
char string[] = "This is an example string\n";
puts(string); // String is variable Here
puts("String"); // String is in Double Quotes
}
Output :
String is : This is an example string
String is : String

putchar() Function:
Syntax :
int putchar(int c);
Way 1 : Taking Character as Parameter

S.KAVITHA / AP / CSE / MSAJCE Page 17 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

putchar('a') ; // Displays : a
Individual Character is Given as parameter to this function. We have to explicitly mention
Character.
Way 2 : Taking Variable as Parameter
putchar(a);
// Display Character Stored in a
Input Parameter is Variable of Type “Character”. This type of putchar() displays character stored
in variable.
Example :
#include< stdio.h>
#include< conio.h>
void main()
{
char string[] = "This is an example string\n";
int i=0;
while(string[i]!='\0')
{
putchar(string[i]);
i++;
}
}

3.6 STRING OPERATIONS / STRING MANIPULATIONS USING


LIBRARY FUNCTIONS
 Strings are often needed to be manipulated by programmer according to the need of a
problem.
 All string manipulation can be done manually by the programmer , this makes programming
complex and large.
 To solve this, the C supports a large number of string handling functions.
 There are numerous functions defined in "string.h" header file. Few commonly used string
handling functions are discussed below:

S.KAVITHA / AP / CSE / MSAJCE Page 18 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Function Work of Function

strlen() Calculates the length of string

strcpy() Copies a string to another string

strcat() Concatenates(joins) two strings

strcmp() Compares two string

strlwr() Converts string to lowercase

strupr() Converts string to uppercase

strstr() Finds the first substring in a string

strncmp() compares at most the first n bytes of str1 and str2.

copies up to n characters from the string pointed to,


strncpy()
by src to dest.

Strlen() FUNCTION:
 strlen() function calculates the length of string. It takes only one argument, i.e, string
name.Defined in Header File <string.h>
Syntax:
temp_variable = strlen(string_name);
 Function strlen() returns the value of type integer.

Example:

S.KAVITHA / AP / CSE / MSAJCE Page 19 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

#include <stdio.h>
#include <string.h>
int main(){
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
char c[20];
printf("Enter string: ");
gets(c);
printf("Length of string a=%d \n",strlen(a));
//calculates the length of string before null charcter.
printf("Length of string b=%d \n",strlen(b));
printf("Length of string c=%d \n",strlen(c));
return 0;
}
OUTPUT:
Enter string: String
Length of string a=7
Length of string b=7
Length of string c=6

strcpy() FUNCTION:
 Function strcpy() copies the content of one string to the content of another string. It takes two
arguments.Defined in Header File <string.h>
Syntax:
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.
Example:
#include <stdio.h>
#include <string.h>
void main(){

S.KAVITHA / AP / CSE / MSAJCE Page 20 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

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);
}
OUTPUT:
Enter string: hello Good Morning
Copied string: hello Good Morning

strcat() FUNCTION:
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.Defined in Header File <string.h>
Syntax:
strcat(first_string,second_string);
Example:
#include <stdio.h>
#include <string.h>
int main(){
char str1[]="This is ", str2[]="Computer programming";
strcat(str1,str2); //concatenates str1 and str2 and resultant string is stored in str1.
puts(str1);
puts(str2);
return 0;
}
OUTPUT
This is Computer programming
Computer programming

strcmp() FUNCTION:

S.KAVITHA / AP / CSE / MSAJCE Page 21 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

 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. Defined in
Header File <string.h>
Syntax:
temp_varaible=strcmp(string1,string2);
Example:
#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");
}
OUTPUT:
Enter first string: Apple
Enter second string: Apple
Both strings are equal.
 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. For
example:
char str1[]="and",str2[]="cat";
temp=strcmp(str1,str2);
 Since, ASCII value of 'a' is less than that of 'c', variable temp will be negative.

S.KAVITHA / AP / CSE / MSAJCE Page 22 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

strlwr() FUNCTION:
strlwr() function converts all the uppercase characters in that string to lowercase characters. The
resultant from strlwr() is stored in the same string.Defined in header file: <string.h>
Syntax:
strlwr(string_name);
Example:
#include <stdio.h>
#include <string.h>
int main(){
char str1[]="LOWer Case";
puts(strlwr(str1)); //converts to lowercase and displays it.
}
OUTPUT:
lower case
Function strlwr() leaves the lowercase characters as it is and converts uppercase characters to
lowercase.

strstr() FUNCTION:
 Finds first occurrence of sub-string in other string
 Checks whether s2 is present in s1 or not. On success, strstr returns a pointer to the element
in s1 where s2 begins. On error (if s2 does not occur in s1), strstr returns null.
Syntax :
strstr(s1, s2);
Example:
#include <stdio.h>
#include <string.h>
void main()
{
const char haystack[20] = "WatherMelon";
const char needle[10] = "Melon";
char *ret;

S.KAVITHA / AP / CSE / MSAJCE Page 23 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

ret = strstr(haystack, needle);


printf("The substring is: %s\n", ret);
}
The substring is: Melon

strncpy() FUNCTION:
Syntax:
strncpy(str1, str2, n)
Case1: If length of str2 > n then it just copies first n characters of str2 into str1.
Case2: If length of str2 < n then it copies all the characters of str2 into str1 and appends several
terminator chars(„\0‟) to accumulate the length of str1 to make it n.
Example:
#include <stdio.h>
#include <string.h>
void main()
{
char first[30] = "string 1";
char second[30] = "string 2: I‟m using strncpy now";
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
}
OUTPUT:
String s1 is: string 2: I‟m

Strncmp() FUNCTION:
strncmp function: int strncmp(const char *str1, const char *str2, size_t n)
It compares both the string till n characters or in other words it compares first n characters of
both the strings.
Example:
#include <stdio.h>
#include <string.h>

S.KAVITHA / AP / CSE / MSAJCE Page 24 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

int main()
{
char s1[20] = "BeginnersBook";
char s2[20] = "BeginnersBook.COM";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
OUTPUT:
string1 and string 2 are equal

3.7 STRING ARRAY:


 Besides data base applications, another common application of two dimensional arrays is to
store an array of strings.
 an array of strings can be declared and operations such as reading, printing and sorting can be
performed on them.
 A string is an array of characters; so, an array of strings is an array of arrays of characters.
The maximum size is the same for all the strings stored in a two dimensional array.
 We can declare a two dimensional character array of MAX strings of size SIZE as follows:
char names[MAX][SIZE];

 Since names is an array of character arrays, names[i] is the character array, i.e. it points

to the character array or string, and may be used as a string of maximum size SIZE - 1.

S.KAVITHA / AP / CSE / MSAJCE Page 25 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

 As usual with strings, aNULL character must terminate each character string in the array. We
can think of an array of strings as a table of strings, where each row of the table is a string as
seen in Figure 9.13.

Example:
Write a C program to search a name in a list of names using binary searching techniques.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int i,n,low,high,mid;
char a[50][50],key[20];
clrscr();
printf(―Enter the number of names\n‖);
scanf(―%d‖, &n);
printf(―enter the names in ascending order \n‖);
for(i=0;i<=n-1;i++)
{
scanf(‖%s‖, &a[i]);
}
printf(―enter the name to be searched\n‖);

S.KAVITHA / AP / CSE / MSAJCE Page 26 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

scanf(―%s‖,&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(strcmp(key,a[mid]) == 0)
{
printf(―key found at the position %d \n‖, mid+1);
getch();
exit(0);
}
else if(strcmp(key,a[mid]) > 0)
{
high = high;
low = mid+1;
}
else
{
low = low;
high = mid-1;
}
}
printf(―name not found\n‖);
getch();
}

OUTPUT:
1. Enter the number of names
5
Enter the names in ascending order

S.KAVITHA / AP / CSE / MSAJCE Page 27 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Dhoni
Dravid
Ganguly
Sachin
Virat
Enter the name to be searched
Sachin
Key found at the position 4.
2. Enter the number of names
5
Enter the names in ascending order
Dhoni
Dravid
Ganguly
Sachin
Virat
Enter the name to be searched
pujara
Name not found .

SIMPLE PROGRAMS
SORTING:
1. BUBBLE SORT:
Write a c program to sort an array of „N‟ numbers using bubble sort.
#include<stdio.h>
void main()

S.KAVITHA / AP / CSE / MSAJCE Page 28 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

{
int a[10],n,i,j,temp;
printf("\n\tenter the size of array:");
scanf("%d",&n);
printf("\n\tEnter the elements of array:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n\tElements of array before sorting are...");
for(i=0;i<n;i++)
{
printf("\n\t%d",a[i]);
}
/* Bubble Sort */
for(i=0;i<n;i++) /* n-1 passes required to sort the entire array */
{
for(j=0;j<n-i-1;j++) /* Compare adjacent elements and exchange if necessary */
{
if(a[j] > a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\n\tElements of array after sorting are...");
for(i=0;i<n;i++)
{
printf("\n\t%d",a[i]);

S.KAVITHA / AP / CSE / MSAJCE Page 29 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

}
printf("\n");
}
OUTPUT:
enter the size of array:5
Enter the elements of array:
66
33
22
88
44
Elements of array before sorting are...
66
33
22
88
44
Elements of array after sorting are...
22
33
44
66
88

2. INSERTION SORT
Write a c program to sort an array of „N‟ numbers using insertion sort
#include<stdio.h>
void main()
{
int a[10],p,j,n,tmp;
printf("Enter the number of elements:\n");

S.KAVITHA / AP / CSE / MSAJCE Page 30 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

scanf("%d",&n);
printf("enter the elements to e sorted:\n");
for(p=0; p<n; p++)
{
scanf("%d",&a[p]);
}
for(p=1; p<n; p++)
{
tmp = a[p];
for(j=p ;j>0 && a[j-1] > tmp ;j--)
{
a[j] = a[j-1];
}
a[j] = tmp;
}

printf("After sorting:\n");
for(p=0; p<n; p++)
{
printf("%d\t",a[p]);
}
}
OUTPUT:
Enter the number of elements:
5
enter the elements to e sorted:
33
22
11
66
44

S.KAVITHA / AP / CSE / MSAJCE Page 31 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

After sorting:
11 22 33 44 66

SEARCHING
1. LINEAR SEARCHING
Write a c program for linear search on a array of ‘N’ numbers
#include <stdio.h>
void main()
{
int array[10];
int i, num, keynum, found = 0,note;
printf("Enter the value of num \n");
scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
scanf("%d", &array[i]);
printf("Input array is \n");
for (i = 0; i < num; i++)
printf("%d\n", array[i]);
printf("Enter the element to be searched \n");
scanf("%d", &keynum);
/* Linear search begins */
for (i = 0; i < num ; i++)
{
if (keynum == array[i] )
{
found = 1;
note=i;
break;
}
}

S.KAVITHA / AP / CSE / MSAJCE Page 32 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

if (found == 1)
printf("Element is present in the position %d\n",note+1);
else
printf("Element is not present in the array\n");
}
OUTPUT:
Enter the value of num
5
Enter the elements one by one
4
7
2
5
1
Input array is
4
7
2
5
1
Enter the element to be searched
4
Element is present in the position 1

2. BINARY SEARCHING
Write a c program for the concept of binary search
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100],i,j,temp;
printf("Enter number of elements\n");

S.KAVITHA / AP / CSE / MSAJCE Page 33 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
/* Bubble sorting begins */
for (i = 0; i < n; i++)
{
for (j = 0; j < (n - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < n; i++)
{
printf("%d\n", array[i]);
}
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {

S.KAVITHA / AP / CSE / MSAJCE Page 34 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

printf("%d found at location %d.\n", search, middle+1);


break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);
return 0;
}

OUTPUT:
Enter number of elements
5
Enter 5 integers
2
5
3
7
1
Sorted array is...
1
2
3
5
7
Enter value to find
1
1 found at location 1

S.KAVITHA / AP / CSE / MSAJCE Page 35 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

MATRIX OPERATIONS.
1. MATRIX TRANSPOSE:
Write a c program to print the transpose of the given matrix
#include<stdio.h>
void main()
{
int m,n,i,j,matrix[10][10],transpose[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d",&m,&n);
printf("\n Enter the elements of the matrix \n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&matrix[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
transpose[j][i]=matrix[i][j];
printf("Transposse of the given matrix:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d\t",transpose[i][j]);
}
printf("\n");
}
}
OUTPUT:
Enter the number of rows and columns of matrix
33

S.KAVITHA / AP / CSE / MSAJCE Page 36 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Enter the elements of the matrix


1 2 3
4 5 6
7 8 9
Transposse of the given matrix:
1 4 7
2 5 8
3 6 9

2. MATRIX MULTIPLICATION:
Write a c program to multiply two matrices and to print the resultant matrix
#include<stdio.h>
main()
{
int a[5][5],b[5][5],c[5][5],i,j,k,m,n,p,q;
printf("\n\tEnter the number of rows and columns for matrix A:");
scanf("%d%d",&m,&n);
printf("\n\tEnter the number of rows and columns for matrix B:");
scanf("%d%d",&p,&q);
if (n==p)
{
printf("\n\tEnter the elements of matrix A:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n\tEnter the elements of matrix B:");
for(i=0;i<p;i++)

S.KAVITHA / AP / CSE / MSAJCE Page 37 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
printf("\n\tElements of matrix C\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("\t%d",c[i][j]);
}
printf("\n");
}
}
else
{
printf("\n");
printf("\n\tMatrix multiplication not possible!!!!!");

S.KAVITHA / AP / CSE / MSAJCE Page 38 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

}
return 0;
}
OUTPUT:
Enter the number of rows and columns for matrix A:3 3
Enter the number of rows and columns for matrix B:3 3
Enter the elements of matrix A:
222
222
222
Enter the elements of matrix B:
333
333
333
Elements of matrix C
18 18 18
18 18 18
18 18 18

Enter the number of rows and columns for matrix A:2 1


Enter the number of rows and columns for matrix B:4 5
Matrix multiplication not possible!!!!!

3. MATRIX ADDITION:
Write a c program to add two matrices and to print the resultant matrix
#include<stdio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],i,j,m,n,p,q;
printf("\n\tEnter the number of rows and columns for matrix:");

S.KAVITHA / AP / CSE / MSAJCE Page 39 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

scanf("%d%d",&m,&n);
printf("\n\tEnter the elements of matrix A:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n\tEnter the elements of matrix B:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\n\tElements of matrix C\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",c[i][j]);
}

S.KAVITHA / AP / CSE / MSAJCE Page 40 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

printf("\n");
}
}
OUTPUT:
Enter the number of rows and columns for matrix:2 2
Enter the elements of matrix A:
1 1
1 1
Enter the elements of matrix B:
3 3
3 3
Elements of matrix C
4 4
4 4

Program to Remove duplicate Element in an Array


Below is a simple and easy to understand program to find and remove any duplicate element
present in specified array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20], i, j, k, n;
printf("\nEnter array size : ");
scanf("%d",&n);
printf("\nEnter %d array element : ", n);
for(i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}
printf("\nOriginal array is : ");

S.KAVITHA / AP / CSE / MSAJCE Page 41 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

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

printf("\nNew array is : ");


for(i=0; i < n; i++)
{
for(j=i+1; j < n; )
{
if(a[j] == a[i])
{
for(k=j; k < n;k++)
{
a[k] = a[k+1];
}
n--;
}
else {
j++;
}
}
}

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


{
printf("%d ", a[i]);
}
getch();
}
OUTPUT:

S.KAVITHA / AP / CSE / MSAJCE Page 42 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Enter array size : 5


Enter 5 array element : 11 13 11 12 13
Original array is : 11 13 11 12 13
New array is : 11 13 12

C program to find maximum element in array


#include <stdio.h>
void main()
{
int array[100], maximum, size, c, location = 1;
printf("Enter the number of elements in array\n");
scanf("%d", &size);
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]);
maximum = array[0];
for (c = 1; c < size; c++)
{
if (array[c] > maximum)
{
maximum = array[c];
location = c+1;
}
}
printf("Maximum element is present at location %d and it's value is %d.\n", location,
maximum);
}

c program to reverse a given string


#include<stdio.h>

S.KAVITHA / AP / CSE / MSAJCE Page 43 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

#include<string.h>
void main() {
char str[100],original[100], temp;
int i, j = 0;

printf("\nEnter the string :");


gets(str);
i = 0;
j = strlen(str) - 1;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
printf("\nReverse string is :%s", str);
}

OUTPUT:
Enter the string :hello
Reverse string is :olleh
Enter the string :royal
Reverse string is :layor

Write a c program to count and print the number of vowels consonants, digits and
whitespaces in the given string.
#include<stdio.h>
void main()
{
int v=0,c=0,d=0,w=0,i;

S.KAVITHA / AP / CSE / MSAJCE Page 44 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

char line[200];
printf("\n enter the string");
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;

else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))


++c;

else if(line[i]>='0'&&c<='9')
++d;

else
++w;
}
printf("Vowels: %d",v);
printf("\nConsonants: %d",c);
printf("\nDigits: %d",d);
printf("\nWhite spaces: %d",w);
}

OUTPUT:
enter the string:
hello good morning 123
Vowels: 6
Consonants: 10
Digits: 3
White spaces: 3

S.KAVITHA / AP / CSE / MSAJCE Page 45 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

Write a c program to find whether a substring is present in the given string.


#include<stdio.h>
void main()
{
char str[80],search[10];
int count1=0,count2=0,i,j,flag;
puts("Enter a string:");
gets(str);
puts("Enter search substring:");
gets(search);
while (str[count1]!='\0')
count1++;
while (search[count2]!='\0')
count2++;

for(i=0;i<=count1-count2;i++)
{
for(j=i;j<i+count2;j++)
{
flag=1;
if (str[j]!=search[j-i])
{
flag=0;
break;
}
}
if (flag==1)
break;
}

S.KAVITHA / AP / CSE / MSAJCE Page 46 of 47


Unit-III GE6151- COMPUTER PROGRAMMING

if (flag==1)
printf("String %s is present in %s", search,str);
else
printf("String %s is NOT present in %s", search,str);
}

OUTPUT:
Enter a string:
hi hello
Enter search substring:
hello
String hello is present in hi hello
Enter a string:
hi hello
Enter search substring:
how
String how is NOT present in hi hello

S.KAVITHA / AP / CSE / MSAJCE Page 47 of 47

You might also like