0% found this document useful (0 votes)
3 views11 pages

c unit 3

best notes

Uploaded by

Amogh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
3 views11 pages

c unit 3

best notes

Uploaded by

Amogh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

UNIT-4

Introduction to Arrays and Strings


Arrays:
Array is a collection of homogeneous data elements or array is a continuous memory location to store
similar type of data elements. The elements of the array are stored in consecutive memory location and are
referenced by an index (subscript). Arrays are used when the application requires multiple data items of the same
data type. All these similar data items are accessed by the same name.
Arrays are classified into two types on the basis of number of subscripts
 Single dimensional Array or scalar Array/ linear array / List.
 Two dimensional or vector Array.
[

Single dimensional array: It is a list of data items represented by only one index. This is also called as scalar array.
The memory locations are allocated or represented either in row wise or column wise.
Syntax: datatype arr_name [size];
Where data type is the any valid C-Language data type,
arr_name is user defined array name,
[size] is the no. of memory locations reserved for the variable or size of the array.
e.g. int A[5];
In this example 5 memory blocks are reserved for the variable A, each memory block occupy two bytes of
memory space. The lower bound of the array is zero.
A

0 1 2 3 4
e.g.:2 float x[5]; Here, x is a floating-point array which can store maximum of 5 real
numbers. char str[25]; Here, str is a character array which can store maximum of 25
characters
Initialization of arrays: There are two ways of initializing a 1D-array:
 Compile-time initialization
 Run-time initialization
Compile-time Initialization: Assigning values to the array during compile time is referred to as compile-time
initialization.
Syntax: datatype variable[size] = {val1,val2,…};
where, datatype can be int, float, char etc.
variable can be a valid identifier
size is an integer constant that indicates maximum no. of elements stored in the array
val1,val2,… are elements of the array
Program to demonstrate compile-time initialization of the array
#include<stdio.h>
void main()
{
int a[5] = {10,15,25,18};
printf(“\n Array Elements are:\n”);
for(i=0;i< 5;i++)
printf(“a[%d] = %d\n”,i,a[i]);
getch();
}
Run-time Initialization: Assigning values to the array during execution time is called run-time initialization.

1
Program to demonstrate Run-time initialization of the array
#include <stdio.h>
void main()
{
int a[10],i,n;
printf(“\nEnter the size of the array: ); scanf(“%d”,&n);
printf(“\nEnter %d elements for the array:\n”,n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\nArray Contents:\n”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
getch();
}
Program to print array elements in reverse order
#include<stdio.h>
int main()
{
int i,n,a[50]; Enter the size of the array: 4
printf(“\nEnter the size of the array: ); scanf(“%d”,&n); Enter 4 elements for the array:
printf(“\nEnter %d elements for the array:\n”,n); 10 2 18 26
for(i=0;i<n;i++) Array Contents in reverse order:
scanf(“%d”,&a[i]); 26 18 2 10
printf(“\nArray Contents in reverse order:\n”);
for(i=n-1;i>=0;i--)
printf(“%d\t”,a[i]);
getch();
}
Program to find the largest element of N array and its position.
# include <stdio.h>
void main()
{
int a[20],i,n,big,pos;
clrscr();
printf("\n Enter n value "); scanf("%d",&n);
printf("\n Enter %d array elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
big=a[0]; Enter n value : 5
pos=0; Enter 5 array elements
for(i=1;i<n;i++) 10 55 3 66 34
{ Largest element is 55
if(a[i]>big) Its position is 1
{
big=a[i];
pos=i;
}
}
printf("\n Largest element is %d",big);
printf("\n Its position is %d",pos);
getch(); }

2
Two - dimensional array(vector array or Table or Rectangular Array):
The two dimensional array consists of two sub-scripts/ two indices. The first sub-script represents the row and
second sub-script represents the column. 2D arrays are used to represent the data in the tabular format.
Syntax: datatype arr_name [rowsize] [columnsize] ;
where, datatype can be int, float, char etc.
variable can be a valid identifier
row_size is an integer constant which indicates the maximum number of rows for the matrix
column_size is an integer constant which indicates the maximum number of columns for the matrix .
int A[3][2];
This statement tells the compiler to allocate 6 memory blocks to the variable A. In other words the matrix
contains 3 rows and 2 columns. By default 2D array elements are represented in memory as row major access or
row major order.
The conventional method of memory representation is as follows
A[0][0] A[0][1]
A[1][0] A[1][1]
A[2][0] A[2][1]
A[0][0] refers to data item in the first row and first column. A[0]
[1] refers to data item in the first row and second column. A[1][0]
refers to data item in the second row and first column. A[1][1]
refers to data item in the second row and second column. A[2][0]
refers to data item in the third row and first column.
A[2][1] refers to data item in the third row and second column.
Initialization of arrays: There are two ways of initializing a 2D-array:
 Compile-time initialization
 Run-time initialization
Compile-time initialization:
2d array initialization: A 2D array is initialized by one of the two ways.
First type e.g.: a[2][3]={3,6,2,10,8,11};
3 6 2
10 8 11
Second type e.g.: a[2][3]={{3,6,2},{10,8,11}};

3 6 2
10 8 11

Program to print 2D ARRAY elements


#include<stdio.h>
void main()
{ Array Elements:
int a[2][2] = {10,15,25,18}; a[0][0] = 10
int i,j; a[0][1] = 15
printf(“\nArray Elements:\n”); a[1][0] = 25
for(i=0;i<2;i++) a[1][1] = 18
for(j=0;j<2;j++)
printf(“a*%d][%d] = %d\n”,i,j,a[i][j]);
getch();
}

3
Program to print 2D ARRAY elements in matrix form
#include<stdio.h>
void main()
{
int a[2][2] = {10,15,25,18};
int i,j; OUTPUT:
printf(“\nMatrix A (2x2):\n”);
Matrix A (2x2):
for(i=0;i<2;i++)
10 15
{
25 18
for(j=0;j<2;j++)
printf(“%4d”,a*i+*j+); printf(“\
n”);
}
getch();
}
Run-time initialization: Assigning values to the array during execution is called Run-time initialization.
int a[3][3],i,j;
for(i=0 ;i<3;i++)
for(j=0;j<3;j++)
scanf(“%d”,&a[i][j]);
Program to demonstrate run-time initialization of the fixed length array
#include<stdio.h>
void main()
{
int a[5][5]; //Fixed length
array int i,j,m,n;
printf(“\nEnter the order of the matrix: ); scanf(“%d%d”,&m,&n);
printf(“\nEnter %d elements for the matrix:\n”,m*n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf(“\nMatrix A (%dx%d):\n”,m,n); Enter the order of the matrix: 2 3
for(i=0;i<m;i++) Enter 6 elements for the matrix:
{ 1 5 2 8 3 7
for(j=0;j<n;j++) Matrix A (2x3):
printf(“%d”,a*i+*j+); printf(“\ 1 5 2
n”); 8 3 7
}
getch();
}
Program to compute the sum of two matrices
#include<stdio.h>
void main()
{
int I,j,a[10][10],b[10][10],c[10][10];
printf(“\Enter 6 elements for the matrix A:\n”,);
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf(“%d”,&a[i][j]);
printf(“\n Enter 6 elements for the matrix B:\n”);
for(i=0;i<2;i++)

4
for(j=0;j<3;j++)
scanf(“%d”,&b[i][j]); OUTPUT:
for(i=0;i<2;i++) Enter 6 elements for the matrix A: 1 5 2 8 3 7
for(j=0;j<3;j++) Enter 6 elements for the matrix B: 4 3 5 6 1 2
c[i][j] = a[i][j] + b[i][j]; Input Matrix A: 1 5 2
printf(“\nInput Matrix A :\n”); 8 3 7
for(i=0;i<m;i++) Input Matrix B : 4 3 5
{ 6 1 2
for(j=0;j<n;j++) Resultant Matrix C : 58 7
printf(“%4d”,a*i+*j+); 14 4 9
printf(“\n”);
}
printf(“\nInput Matrix B :\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf(“%4d”,b*i+*j+);
printf(“\n”);
}
printf(“\nResultant Matrix C:\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf(“%4d”,c*i+*j+);
printf(“\n”);
}
getch();
}
Write a program to find the transpose of a matrix
STRINGS: It is a character array terminated by NULL character. In the declaration statement, character
array and strings are one and the same. Character array and string are differentiated only after data
input. A character array doesn’t end with a NULL character, but string ends with NULL character.
Declaration: Syntax: char variable[size];
where, variable can be any valid identifier
size is an integer constant which indicates the maximum number of characters that can be stored in the
array including NULL character
Total memory allocated for the variable = size * sizeof(datatype)
e.g.: char str[20];
Here, str is a string variable which can store maximum of 20 characters.
Total memory allocated for the array str is 20 * 1 = 20 bytes
Initializing a string variable: There are two ways of initializing a string:
 Compile-time initialization
 Run-time initialization
1. Compile-time initialization
Assigning values to the string during compile time is referred to as compile-time initialization.
i. character constant :
Char Str [10] = {‘P’,’U’,’N’, ‘E’,’E’,’T’’H’,’\0’};
In this method user has to specify the NULL character.
ii. String constant:
Char str[10] =“ PUNEETH ”;
In this method complier itself introduces the NULL character at the end.
5
2. Run-time initialization
Run-time initialization of string by reading strings from terminal using scanf() function or gets() function.
Using formatted input function - scanf() with %s format specifier
#include <stdio.h>
void main()
{
char str[25];
printf(“\nEnter a string: “); scanf(“%s”,str); Enter a string: PUNEETH
printf(“\nThe Entered string is \“%s\””,str); The Entered string is “PUNEETH”
getch();
}
a. Unformatted I/O function, gets() : It is an unformatted input function used to read a string through the
standard input device (keyboard). It is used to read one line of text. The prototype for this function is available
in <stdio.h> .
Syntax: gets(string_variable);
where, string_variable is a valid array name of character data type.
e.g.: char str[20];
gets(str)
#include <stdio.h>
void main()
{
char str[25];
printf(“\nEnter a string: “); gets(str);
Enter a string: Cs-Lab
printf(“\nThe Entered string is \”%s\””,str);
getch(); The Entered string is “Cs-Lab”
}
Unformatted I/O functions puts()
It is an unformatted output function used to display a string on to the standard output device (Monitor). The
prototype for this function is available in <stdio.h> header file.
Syntax: puts(str);
where, str can be a string variable of character data type or a string constant.
e.g.: char str[30]=”BSc”;
puts(str);
String Handling Functions: These are the library functions used for manipulating strings. All String handling
functions are available in <string.h> header file.
strlen() : It is used to count the number of characters in the string. strlen() returns integer data. The length does
not include the NULL character.
Syntax: n = strlen(string);
• It receives one argument which can be either a string variable or a string constant.
• It returns an integer value which indicates the number of characters in the string which is passed as argument. It
doesn’t include NULL character.
e.g.: char str[] = “Hello”;
int m,n;
m = strlen(str); //m holds the value 5
n = strlen(“1234”); // n holds the value 4

Program to find the length of the string using Built-in String function
#include <stdio,h>
#include <string.h>
void main()

6
{
char str[30]; Enter a string:
int length; BCA-BSc
printf("Enter a string:\n"); gets(str); Length of string, “BCA-BSc” = 7
length = strlen(str);
printf("\nLength of string, \”%s\” = %d”,length);
getch();
}
strcpy(): It is used to copy the contents of one string to another. It makes a duplicate of the existing string. It is also
used to initialize the string.
Syntax: strcpy(string2,string1);
• It receives 2 arguments where, 1st argument (string2) is the destination and 2nd argument (string1) is the source.
• First argument must be a string variable. Second argument can be either a string constant or a string variable.
• It copies all the characters in source string to the destination string including NULL character.
• Only destination string is modified. Source string is unaffected.
e.g.: char str1[20]=”BCA”,str2[20];
strcpy(str2, str1); // copy the content of str1 to str2 . Str2 contains “BCA”
Program to copy the content of one string to another using Built-in string function
#include <stdioh>
#include <string.h>
int main()
{
char str1[30],str2[30]; Enter a string:
printf("Enter a string:\n");gets(str1); strcpy(str2,str1); PUNEETH
printf("\nInput string:\n%s\n”,str1); printf("\ Input string: PUNEETH
nResultant string:\n%s”,str2); Resultant string: PUNEETH
getch();
}
strcat(): This function is used to combine / concatenate two strings into a single string. In other words add the
content of second string to the end of the first string. It is also called as merging of two strings.
Syntax: strcat(string2,string1);
• It receives 2 arguments where, 1st argument (string2) is the destination and 2nd argument (string1) is the source.
• First argument must be a string variable. 2nd argument can be either a string constant or a string variable.
• It appends all the characters in source string including NULL character to the destination string at the end.
• It returns the base address of the destination string.
• Only destination string is modified. Source string is unaffected.
e.g.: char str1[20] =“BCA”, str2[20] =“BSC”;
strcat(str2,str1); //str2 holds “BSCBCA”
Program to concatenate two strings using built-in string function
#include <stdio.h>
#include <string.h>
void main()
{
char str1[30],str2[30]; Enter first string: BCA
printf("Enter first string:\n"); gets(str1); Enter second string: BSC
printf(“\nEnter second string:\n"); gets(str2); String1: BCABSC
strcat(str1,str2); String2: BSC
printf("\nString1: %s\n”,str1);
printf("\nString2: %s”,str2);
getch(); }
7
strcmp() : This function is used to compare two strings with case sensitive, which returns an integer.
Syntax: n = strcmp(string1,string2);
• It receives two arguments which can be either string constants or string variables.
• It returns an integer value as follows:
If string1 < string2 then it returns negative value (-1)
If string1 == string2 then it returns zero
If string1 > string2 then it returns positive value (+1)
e.g.: char str1[10]=“abc”,str2[10]=“abc”;
int n;
n = strcmp(str1,str2); //n holds the value zero since strings are equal.

Program to check whether two strings are equal or not, using Built-in string function
#include <stdio.h>
#include <string.h>
void main() Output1:
{
char str1[30],str2[30]; Enter first string:
printf("Enter first string:\n"); gets(str1); abc
printf(“\nEnter second string:\n"); gets(str2); Enter second string: abd
if(strcmp(str1,str2)==0) Strings are not equal
printf(“\nStrings are equal”); Output2:
else Enter first string:
printf(“\nStrings are not equal”); abc
getch(); Enter second string: abc
} Strings are equal

strrev(): It is used to reverse the given string.


Syntax: strrev(string);
• It receives one argument which must be a string variable.
• It stores the characters of the specified string in reverse order and appends NULL character at the end.
• It returns the base address of the string specified as argument.
• The string variable specified as argument gets modified.
e.g.: char str[20]=“BCA”;
strrev(str); //str holds “ACB”

Program to reverse the string using built-in string function


#include <stdio.h>
#include <string.h>
void main()
{
char str[30]; Output:
printf("Enter a string:\n"); gets(str); Enter a string:
printf(“\nBefore reversing, string is \”%s\”\n“,str); BCA
strrev(str); Before reversing, string is “BCA”
printf(“\nAfter reversing, string is \”%s\”“,str); After reversing, string is “ACB”
getch();
}

8
Program to reverse the given string & check whether it is a palindrome or not, using built-in string function
#include <stdio.h>
#include <string.h>
void main()
Output1:
{
char str1[30],str2[30]; Enter a string: BSC
printf("Enter a string:\n"); gets(str1); String “CSB” is not a palindrome
strcpy(str2,str1); Output2:
strrev(str2); Enter a string: POP
if(strcmp(str1,str2) == 0) String “POP” is a palindrome
printf(“\nString \”%s\” is a palindrome”,str1);
else
printf(“\nString \”%s\” is not a palindrome”,str1);
getch();
}
Character handling functions:
These functions are used to operate on character data types. For all character handling functions, the header file
ctype.h is used . Hence the preprocessor directive is #include <ctype.h>.
There are 2 types of character manipulation functions
1. Classification functions
2. Conversion functions
Classification functions: The classification function begins with the prefix –is and used to determine the type of the
character. Hence these functions classify the character as upper case, lower case, digit or special symbol.
Function Descripti Exampl
on e
isalnum(char) Tests whether a character is an isalnum(‘+’);  0
alphanumeric or not isalnum(‘9’);  1
isalnum(‘B’);  1
isalpha(char) Tests whether a character is an alphabet isalpha(‘A’);  1
or not isalpha(‘7’);  0
isdigit(char) Tests whether a character is a numerical isdigit(‘B’);  0
digit or not isdigit(‘4’);  1
islower(char) Tests whether a character is lower case islower(‘B’);  0
alphabet or no islower(‘e’);  1
isupper(char) Tests whether a character is upper case isupper(‘B’);  1
alphabet or no isupper(‘e’);  0
isspace(char) Tests whether a character is white space isspace(‘\n’);  1
character or not [space, tab, new line ] isspace(‘b’);  0
Conversion functions: The conversion function begins with the prefix –to and used to convert one type of the
character to another.
Function Descripti Exampl
on e
toascii(char) Translate character to ASCII value toascii(‘A’);  65
toascii(‘2’);  50
tolower(char) Translate upper case alphabet to lower tolower(‘B’)  ‘b’
case alphabet tolower(‘b’);  ‘b’

9
toupper(char) Translate lower case alphabet to upper toupper(‘B’)  ‘B’
case alphabet toupper(‘b’);  ‘B’

10
Program to read a string and count the no. of lower case alphabets, upper case
alphabets, digits, blank spaces in the string using character type function
#include <stdio.h>
#include <ctype.h>
void main()
{
char str[25];
int i,count1=0,count2=0,count3=0,count4=0,count5=0;
printf("Enter a string:\n"); gets(str); for(i=0;str[i]!
=NULL;i++)
{
if(islower(str[i]))
count1++; Enter a string:
else if(isupper(str[i])) C Programming Part-3
count2++; No. of Lower case alphabets = 13
else if(isdigit(str[i])) No. of Upper case alphabets = 3
count3++; No. of digits = 1
else if(isspace(str[i])) No. of spaces = 2
count4++; No. of Special Character = 1
else
count5++;
}
printf("\nNo. of Lower case alphabets = %d",count1);
printf("\nNo. of Upper case alphabets =
%d",count2); printf("\nNo. of digits = %d",count3);
printf("\nNo. of spaces = %d",count4); printf("\
nNo. of special character = %d",count5); getch();
}
Program to convert lower case characters to upper case & vice versa using character type functions
#include <stdio.h>
#include <ctype.h>
void main()
{
char str[25];
int i;
printf("Enter a string:\n"); gets(str);
for(i=0;str[i]!=NULL;i++) Enter a string:
{ TOggLE
if(isalpha(str[i])) Resultant String:
{ toGGle
if(islower(str[i]))
str[i] = toupper(str[i]);
else str[i] = tolower(str[i]);
}
}
printf("\nResultant String :\n%s",str);
getch();
}

*************

11

You might also like