cps-3 (1)

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 83

C PROGRAMMING

FOR PROBLEM SOLVING


(18CPS23)
Module 3
ARRAYS,STRINGS

Prof. Mahalakshmi C V, Assistant Professor, CSE, BIT


Email: mahalakshmicv@gmail.com
Website: https://sites.google.com/site/mahalakshmicvbitcse
INTRODUCTION
i=0 i=0
i++ i++
i<9 i<9

T T
F

Read a[i] Print a[i]

stop stop
Searching
• The process of finding a particular item in the large amount of data
is called searching.
• The element to be searched is called key element. There are two
methods of searching:
• Linear search.
• Binary search.
• Advantages of binary search
• Simple technique
• Very efficient searching technique Disadvantages
• The elements should be sorted.
• It is necessary to obtain the middle element, which are stored in array. If
the elements are stored in linked list, this method cannot be used.
#include<stdio.h>
Write a C program to find the key element using Binary search.
Void main()
{
int num[10],n,key,mid,low,high,I,success=0;
printf(“enter the number of element into the array\n”);
scanf(“%d”,&n);
printf(“enter the elements\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&num[i]);
}
printf(“enter the key\n”);
scanf(“%d”,&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
Linear Search

– Linear search also called sequential search is a simple searching


technique.
– In this technique we search for a given key item in linear order i.e, one
after the other from first element to last element.
– The search may be successful or unsuccessful.
– If key item is present, the search is successful, otherwise unsuccessful
search.
• Advantages of linear search
• Very simple Approach.
• Works well for small arrays.
• Used to search when elements are not sorted.

• Disadvantages of linear search
• Less efficient if array size is large
• If the elements are already sorted, linear search is not efficient.
Sorting

• The process of arranging elements in either ascending order or descending


order is called Sorting.

Bubble Sort
• This is the simplest and easiest sorting technique.
• In this technique two successive elements of an array such as a[j] and
a[j+1] are compared.
• If a[j]>=a[j+1] the they are exchanged, this process repeats till all elements
of an array are arranged in ascending order.
• After each pass the largest element in the array is sinks at the bottom and
the smallest element in the array is bubble towards top. So this sorting
technique is also called as sinking sort and bubble sort.
Bubble Sort
Program to sort the given number using bubble sort

#include<stdio.h>
void main()
{
int a[20],n,.temp,i,j;
printf(“enter the number of elements\n”):
scanf(“%d”,&n);
printf(“enter the unsorted array elements\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
If( a[ J ] > a[ J+1 ] )
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf(“the sorted elements arer\n”);
for(i=0;i<n;i++)
printf(“ %d\t”, a[i]);
}
Selection Sort
Write a C program to evaluate the polynomial using
Horners method.

#include<stdio.h>
void main()
{
int i,x,n,a[10],sum;
printf(“enter n:\n”);
scanf(“%d”,&n);
printf(“enter n+1 co efficient\n”);
for(i=0; i<=n;i++)
{
scanf(“%d”,&a[i]);
}
sum=a[n]* x;
for(i=n-1; i>0; i--)
{
sum=(sum+a[i]) *x;
}
sum=sum+a[0];
printf(“sum of polynomial equation is %d”,sum);
}
Multidimensional Array
Write a c program to read & print 2d array as a
Array.
#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“eneter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“array elements are\n”); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}
}
Write a c program to add two matrices.

#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3],b[3][3] ,c[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array a elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter array b elements\n”);
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(“resultant matrix c is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
Write a c program to copy one 2d array in to
another 2d array
#include<stdio.h>
void main()
{
int m,n,i,j,a[3][3],b[3][3];
clrscr();
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array a elements\n”);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf(“%d”, &a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=a[i][j];
}
}
printf(“matrix b is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
Write a c program to find biggest element in a
matrix or 2D array.
#include<stdio.h>
void main()
{

int m,n,i,j,a[3][3]; clrscr();


printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
big=a[0][0];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(big>a[i][j])
big=a[i][j];
}
}
printf(“big is %”,big);
}
Write a program to find sum of each row and
sum of each column
#include<stdio.h>
void main()
{
int m,n,i,j,rsum,csum,a[3][3];
printf(“enter number of rows and columns\n”);
scanf(“%d %d”,&m,&n);
printf(“enter array elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<m;i++)
{
rsum=0;
for(j=0;j<n;j++)
{
rsum=rsum+a[i][j];
}
printf(“sum is %d”,rsum);
}
for(i=0;i<m;i++)
{
csum=0;
for(j=0;j<n;j++)
{
csum=csum+a[i][j];
}
printf(“sum is %d”,csum);
}
}
Write a C program to implement Matrix
Multiplication
#include<stdio.h>
void main()
{
int m,n,i,j,sum,p,q,k,a[3][3],b[3][3],c[3][3];
printf(“enter number of rows and columns of matrix a \n”);
scanf(“%d %d”,&m,&n);
printf(“enter number of rows and columns of matrix b \n”);
scanf(“%d %d”,&p,&q);
if(n!=p)
{
printf(“multiplication not possible\n”);
exit(0);
}

printf(“enter matrix a elements\n”);


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
printf(“enter array b elements\n”);
for(i=0;i<p;i++)
{
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(“resultant matrix A is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
printf(“resultant matrix B is \n”);
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}
printf(“resultant matrix a is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
STRINGS

• A group of characters together is called String.


• String is always enclosed within double quotes (“ “)
• String always ends with delimiter (NULL – ‘\0’ )
• Ex: a = “BIT”

Operations on string:
• Reading and writing a string
• Combining string together
• Copying one string to another
• Comparing string for equality
• Extracting a portion of string
DECLARATION OF A STRING
• A String is declared like an array of character.
Syntax: data_type string_name[size];
• Example: char name[20];
• String size 20 means it can store upto 19 characters plus the NULL
character.

INITIALIZATION OF A STRING
• Syntax: data_type string_name[size] = value;
• Example: The String can be initialized in two ways:
i. char name[30] = “SUVIKA”;
ii. char name[30] = {‘S’, ‘U’, ‘V’, ‘I’, ‘K’, ‘A’, ‘\0’};
NOTE:
i. char a[2] = “CPPS”; The above initialization is invalid because, the size
is less.
ii. char a[5];
iii. a = “CPPS”; The above initialization is invalid because, in string the
declaration and initialization should be done together.
LIMITATION OF STRINGS
One string variable cannot be directly assigned to another variable as shown below:
char name1[10] = “Hello”;
char name2[10];
name2 = name1; //Invalid
But, this initialization can be done using a loop and assigning a individual character as
shown below:
#include <stdio.h>
void main( )
{
char name1[10] = “Hello”;
char name2[10];
int i;
for(i=0; i<5;i++)
{
name2[i]=name1[i];
}
name2[i]=‘\0’;
}
READING AND WRITING A STRING

Reading a String:
To read a string we use %s specifier.
Ex: char name[10];
printf(“Enter the name\n”);
scanf(“%s”, name);
While reading strings we need not specify address operator because, character
array itself is an address.
• NOTE:
Edit set conversion code %[ ]
It is used to specify the type of character that can be accepted
by scanf function.
• Ex 1: char name[20];
scanf(“%[0123456789]”, name);
Example 1 specifies that it accepts only numbers.
• Ex 2: char name[20];
scanf(“%[^0123456789]”, name);
Example 2 specifies that it accepts only alphabets, special
symbols, space but it does not accept any number.
• Ex 3: char name[20];
scanf(“%[A-Z]”, name);
Example 3 specifies that it accepts only upper case alphabets.
Writing/Printing a String:
We can use print function with %s format specifier to print a string. It
prints the character until NULL character.
• Ex 1: char name[10] = “SUVIKA”;
printf(“The name is %s”, name);
Output: The name is SUVIKA
• Ex 2: char name[10] = “SUVIKA”;
printf(“%s”, name);
printf(“%9.3s”, name);
printf(“%-10.3s”, name)
STRING MANIPULATION FUNCTIONS

C library supports a large number of string handling functions that can be


used to carry out many of string manipulation and are stored in header file
• There are mainly 6 string handling functions:
I. strcpy( ) – String Copy
It is possible to assign the value to a string variable using
strcpy( ).
It allows us to copy one string from one location to another.
Syntax: strcpy(destination, source);
This function has two parameters:
i. destination: A string variable whose value is going to
be changed.
ii. source: A string variable which is going to be copied
to destination.
Ex: char a[10], b[10];
strcpy(a, “BIT”);
strcpy(b, a);
After two calls to strcpy( ) a, b contains BIT.
II. strlen( ) – String Length
The string length function can be used to find the length of the string in bytes.
Syntax: length = strlen(str);
String length function has one parameter str which is a string.It returns an
integer value.
Ex: char str[10] = “BIT”;
int length;
length = strlen(“bit college”); // 11
Note: str = ‘\0’
length = strlen(str); //0
III. strcmp( ) – String Compare
It is used to compare two strings.
It takes the two strings as a parameter and returns an integer value.
Syntax: result = strcmp(first, second);
result = 0 first = second
result > 0 first > second
result < 0 first < second
Example: int res;
res = strcmp(“cat”, “car”); //res > 0
res = strcmp(“pot”, “pot”); //res = 0
res = strcmp(“big”, “small”); //res < 0
IV. strcat( ) – String Concatenate
It is used to concatenate or join two strings together. It has two parameters
where the combined string will be stored in the (destination) first
parameter.
Syntax: strcat(destination, source);
Example: char first[30] = “Computer”;
char last[30] = “Programming”;
strcat(first, last);
Note: strcat( ) stops copying when it finds a NULL character in the second
string.
V. strncmp( ) – String ‘n’ Compare
It compares upto specify number of characters from the two
strings and returns integer value.
Syntax: result = strncmp(first, second, n);
result = 0 first = second
result > 0 first > second
result < 0 first < second
Example: int res;
res = strncmp(“string”, “stopper”, 4); //res > 0
res = strncmp(“string”, “stopper”, 2); //res = 0
res = strncmp(“stopper”, “string”, 4); //res < 0
VI. strncpy( ) – String ‘n’ Copy
This function allows us to extract a substring from one string and
copy it to another location.
Syntax: strncpy(dest, source, numchars);
The strncpy( ) takes three parameters. It copies the number of
characters (numchars) from source string to destination string.
Since, numchars doesn’t include NULL character we have to
specify explicitly.
Ex: char a[10] = “BIT”;
char b[10];
strncpy(b, a, 2);
b[2] = ‘\0’
• Strchr():string search
– Syntax: strchr(string_data,searching_character);
– Ex: strchr(“Bangalore”,’l’); //returns lore

• Strlwr()
– Syntax: strlwr(string);
– Ex: strlwr(“BIT”); //RETURNS bit
• Strupr()
– Syntax: strupr(string);
– Ex:strupr(“bit”); //returns BIT
• Strrev()
– Stntax: strrev(string);
– Ex: strrev(“BIT”) //returns TIB
• strset():
– strset(string,character);
– Ex: strset(“BIT”,’*’); // returns ***
• Strnset()
– Syntax: strnset(string,character,n);
– Ex: strnset(“BIT”,’$’,2); // returns $$T
Unformatted Input and output Functions: getchar()
and putchar()
• The int getchar(void) function reads the next available character from the keyboard and
returns it as an integer. This function reads only single character at a time. You can use this
method in the loop in case you want to read more than one character from the screen.
• The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time. You can use this method in the
loop in case you want to display more than one character on the screen.
Ex: #include <stdio.h>
int main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
return 0;
}
Unformatted input and output functions: getc() and
putc()
getc()
The C library function int getc(FILE *stream) gets the next character (an
unsigned char) from the specified stream and advances the position indicator
for the stream.
Declaration
Following is the declaration for getc() function.
int getc(FILE *stream)
Parameters
stream -- This is the pointer to a FILE object that identifies the stream on
which the operation is to be performed. It should be stdin if we want to read
data from keyboard.
Return Value
This function returns the character read as an unsigned char cast to an int or
EOF on end of file or error.
putc()
The C library function int putc(int ch, FILE *stream) writes a character (an
unsigned char) specified by the argument ch to the specified stream and
advances the position indicator for the stream.
Declaration
Following is the declaration for putc() function.
int putc(int ch, FILE *stream)
Parameters
char -- This is the character to be written. The character is passed as its int
promotion.
stream -- This is the pointer to a FILE object that identifies the stream
where the character is to be written. It should be stdout to write on screen.
Return Value
This function returns the character written as an unsigned char cast to an
int or EOF on error.
The following example shows the usage of getc() and putc() function.

#include <stdio.h>
int main()
{
char c;
printf("Enter character: ");
c = getc(stdin);
printf("Character entered: ");
putc(c, stdout);
return(0);
}
Output:
Enter character: A
Character entered: A
Unformatted Input Functions: gets() and puts()

• The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until
either a terminating newline or EOF (End of File). It makes null-terminated string after
reading. Hence it is also known as line-to-string input function.
• The int puts(const char *s) function writes the null-terminated string 's' from memory and a
trailing newline to stdout. This function is also known as string-to-line output function.
#include <stdio.h>
int main( )
{
char str[100];
printf( "Enter a value :");
gets( str );
printf( "\nYou entered: ");
puts( str );
return 0;
}
Output:
Enter a value : I am reading a line
You entered : I am reading a line
• WACP to copy a string (combination of digits and alphabets) to another string (only alphabets).
#include <stdio.h>
#include <ctype.h>
void main()
{
char s1[100], s2[100];
int i=0, j=0;
printf("Enter String1\n");
scanf("%s",s1);
while(s1[i] != '\0')
{
if(isalpha(s1[i]))
{
s2[j] = s1[i];
j++;
}
i++;
}
s2[j] = '\0';
printf("The copied string is %s\n", s2);
}
• C program to read a sentence and count the frequency of VOWELs and total count of consonants.
#include <stdio.h>
int main()
{
char sentence[100];
int vowelA=0, vowelE=0, vowelI=0, vowelO=0, vowelU=0, cons=0;
printf(“Enter a sentence\n”);
gets(sentence);
i=0;
while((ch=sentence[i++])! = „\0‟)
{
switch(ch)
{
case „a‟:
case „A‟: vowelA++; break;
case „e‟:
case „E‟: vowelE++; break;
case „i‟:
case „I‟: vowelI++; break;
case „o‟:
case „O‟: vowelO++; break;
case „u‟:
case „U‟: vowelU++; break;
default: cons++;
}
printf(“Frequency of Vowel A = %d\n” , vowelA);
printf(“Frequency of Vowel E = %d\n” , vowelE);
printf(“Frequency of Vowel I = %d\n” , vowelI);
printf(“Frequency of Vowel O = %d\n” , vowelO);
printf(“Frequency of Vowel U = %d\n” , vowelU);
printf(“Total count of Consonants = %d\n” , cons);
return 0;
}
Write a C program to find reverse of a string without strrev().
#include <stdio.h>
int main()
{
char s[1000], r[1000];
int begin, end, count = 0;
printf("Input a string\n");
scanf(“%s”,s);
// Calculating string length
while (s[count] != '\0')
count++;
end = count - 1;
for (begin = 0; begin < count; begin++) {
r[begin] = s[end];
end--; B I T \0
}
r[begin] = '\0'; 0 1 2 3
printf("%s\n", r);
T I B \0
}
SAMPLE PROGRAMS

You might also like