0% found this document useful (0 votes)
30 views33 pages

PPS FINAL UNIT-2 Notes

Program for Problem Solving Unit 2 notes

Uploaded by

mkukareem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views33 pages

PPS FINAL UNIT-2 Notes

Program for Problem Solving Unit 2 notes

Uploaded by

mkukareem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT – 2

PRECENDENCE AND ASSOCIATION RULES AMONG OPERATORS


 Precedence is used to determine the order in which different operators in a complex expression are
evaluated.
 Associativity is used to determine the order in which operators with the same precedence are valuated in a
complex expression.
 Precedence is applied before the associativity to determine the order in which expressions are evaluated.
Associativity is then applied, if necessary.
 Every operator has a precedence.
 The operators which has higher precedence in the expression is evaluated first.
Example: a=8+4*2;
a=?

Precedence and Associativity of Operators in C (from higher to lower)

1
Example program to illustrate operator precedence

Associativity:
 Associativity can be left-to-right or right-to-left.
 Left-to-right associativity evaluates the expression by starting on the left and moving to the right.
 Right-to-left associativity evaluates the expression by starting on the right and moving to the left.
 Remember, associativity is used only when there are operators with same precedence level in occur in a
complex expression.

2
CONDITIONAL BRANCHING (DECISION CONTROL STATEMENTS)
 Decision is nothing but selecting the right choice between multiple alternatives.
 In computers always the decision will be made based on conditions, for a condition there are two
possibilities, either true or false.
 Always for every possibility of the decision, there will be action or set of actions defined. Based on the
condition result the possible path way will be selected.
 The decision is described to the computer as a conditional statement that can be answered either true or
false.
 If the answer is true, one or more action statements are executed.
 If the answer is false, then a different action or set of actions is executed.
Types of decision control structures:
 if
 if..else
 nested if…else
 else if ladder
 dangling else
 switch statement

Decision Control Statement: if


The general form of a simple if statement is:

if (condition)
{
Following are the properties of an if statement: statement-
 block;will be executed.
If the condition is true then the statement-block
 If the condition is false it does not do anything ( or the statement is skipped)


}
The condition is given in parentheses and must be evaluated as true (nonzero value) or false (zero value).
If a compound statement is provided, it must be enclosed in opening and closing braces.
Flowchart

3
Ent
er
Co
Bodyndit
of the IF
ion
Statement
Exi
Example: t
main()
{
int a=10,b=20;
if(a>b)
{
printf(“%d”,a);
}
printf(“%d”,b);
}

Decision Control Statement: if..else

 The expression or condition which is followed by if statement must be enclosed in parenthesis.


 No semicolon is needed for an if…else statement.
 Both the true and false statements can be any statement (even another if…else).
 Multiple statements under if and else should be enclosed between curly braces.
 No need to enclose a single statement in curly braces.
Decision Control Statement: if..else

4
A Simple if...else Statement

Compound Statements in an if...else


Example Program for Decision Control Statement: if..else

Decision Control Statement: nested if…else

Nested if…else Statements


 Nested if…else :means within the if…else you can include another if…else either in if block or else block.

Example Program for Decision Control Statement: if..else

5
Decision Control Statement: else if ladder

if (condition1)
statements1;
else if (condition2)

statements2;
else if
(condition3)

 statements3;
The conditions are evaluated from the top to down.

else if
6
(condition4)
 As soon as a true condition is found the statement associated with it is executed and the control is
transferred to the statements by skipping the rest of the ladder.
 When all n conditions become false, final else containing default statement that will be executed.

Example program for else if

7
void main()
{
float m1,m2,m3,m4;
float perc;
printf(“enter marks\n”);
scanf(“%f%f%f
%f”,&m1,&m2,&m3,&m4);
perc=(m1+m2+m3+m4)/
4;
if(perc>=75)
printf(“\
nDistinction”);
else if(per<75 &&
per>=60)
printf(“\
nFirst Class”);
else if(per<60 &&
per>=50)

printf(“\nSecond Class”);
else
if(per<50 && per>=40)

printf(“\nThird Class”);

else

printf(“\nFail”);
8
}//main
Dangling else problem:

Dangling else To avoid


else is always paired with the most recent unpaired if.

dangling else
problem place the
inner if stat ement e
Da ngl ing elsthe
with in
Dangling else curDan g else
glinces
ly bra .
Decision Control Statement: switch Solution
 It is a multi-way conditional statement


generalizing the if…else statement.
It is a conditional control statement that allows
(contd…)
some particular group of statements to be chosen from several available groups.
 A switch statement allows a single variable to be compared with several possible case labels, which are
represented by constant values.
 If the variable matches with one of the constants, then an execution jump is made to that point.
 A case label cannot appear more than once and there can only be one default expression.
 Note: switch statement does not allow less than ( < ), greater than ( > ).
 ONLY the equality operator (==) is used with a switch statement.
 The control variable must be integral (int or char) only.
 When the switch statement is encountered, the control variable is evaluated.
 Then, if that evaluated value is equal to any of the values specified in a case clause, the statements
immediately following the colon (“:”) begin to run.
 Default case is optional and if specified, default statements will be executed, if there is no match for the
case labels.
 Once the program flow enters a case label, the statements associated with case have been executed, the
program flow continues with the statement for the next case. (if there is no break statement after case label.)

9
General format of switch:

 The following results are possible, depending on the value of printFlag.


 If printFlag is 1, then all three printf statements are executed.
 If printFlag is 2, then the first print statement is skipped and the last two are executed.
 Finally, if printFlag is neither 1 nor 2, then only the statement defined by the default is executed.

Example1 for switch statement:

 If you want to execute only one case-label, C provides break statement.


 It causes the program to jump out of the switch statement, that is go to the closing braces (}) and continues
the remaining code of the program.
 If we add break to the last statement of the case, the general form of switch case is as follows:
General format of switch:

10
Example 2 for switch statement:

Concept of a loop:
 The real power of computers is in their ability to repeat an operation or a series of operations many times.
 This repetition, called looping, is one of the basic structured programming concepts.
 Each loop must have an expression that determines if the loop is done.
 If it is not done, the loop repeats one more time; if it is done, the loop terminates.

Pretest and Post-test Loops:


 We need to test for the end of a loop, but where should we check it—before or after each iteration, we can
have either a pre- or a post-test terminating condition.
 In a pretest loop, the condition is checked at the beginning of each iteration.

11
 In a post-test loop, the condition is checked at the end of each iteration.

Initialization and Updating:


 In addition to the loop control expression, two other processes, initialization and updating, are associated
with almost all loops.
1) Loop Initialization 2) Loop Update
 Control expression is used to decide whether the loop should be executed or terminated.
 Initialization is place where you can assign some value to a variable.
 Variable’s value can be updated by incrementing a value by some amount.

Loops in C
 C has three loop statements: the while, the for, and the do…while. The first two are pretest loops, and the
third is a post-test loop.
 A looping process, in general, would include the following four steps:
1) Before a loop start, the loop control variable must be initialized; this should be done before the first
execution of loop body.
2) Test for the specified condition for execution of the loop, known as loop control expression.
3) Executing the body of the loop, known as actions.
4) Updating the loop control variable for performing next condition checking.

While loop: is a generalized looping structure that employs a variable or expression for testing the
condition.
 It is a repetition statement that allows an action to be repeated while some conditions remain true.
 The body of while statement can be a single statement or compound statements.
 It doesn’t perform even a single operation if condition fails.

The while Statement

12
Compound while Statement

Example 1: To print 1 to 10 natural numbers


#include<stdio.h>
void main()
{
int i;
i=1;
while (i<=10)
{
printf(“%d\n”,i);
i++;
}
}

Example 2: To print the reverse of the given number.


#include<stdio.h>
void main()
{
int n,m, rem, rev = 0;
printf("\n Enter a positive number: ");
scanf("%d",&n);
m=n;
while(n != 0)
{
rem = n%10;
rev = rev*10+rem;
n = n/10;
}
printf("The reverse of %d is %d\n",m,rev);
}

13
do while: is a repetition statement that allows an action to be done at least once and then the condition is
tested.
 On reaching do statement, the program proceeds to evaluate the body of the loop first.
 At the end of the loop, condition statement is evaluated.
 If the condition is true, it evaluates the body of the loop once again.
 This process continues up to the condition becomes false.

Example 3: To print fibonacci sequence for the given number using do while statement
#include<stdio.h>
void main()
{
int a=0,b=1,c,i;
i=1;
printf("%d %d",a,b);
do
{
c=a+b;
i++;
printf("%3d",c);
a=b;
b=c;
}while(i<=10);
}

Example 4: To print multiplication table for 5 using do while statement.


14
#include <stdio.h>
void main()
{
int i = 1, n=5;
do
{
printf(“%d * %d = %d \n”, n, i, n*i);
i = i + 1;
} while ( i<= 5);
}

for loop: is a repetitive statement used when a loop is to be executed a known number of times.

 We can do the same thing with a while loop, but the for loop is easier to read and more natural for counting
loops.
General form of the for is:
for( initialization; test-condition; updation)
{
Body of the loop
}

for statement compound for statement

15
We can write the for loop in the following ways:
Option 1:
for(k=1;k<=10;)
{
printf(“%d”, k);
k = k + 1;
}
Here the increment is done within the body of the for loop and not in the for statement. Note that the semicolon
after the condition is necessary.

Option 2:
int k = 1;
for (; k< = 10; k++)
{
printf(“%d”, k);
}
Here the initialization is done in the declaration statement itself, but still the semicolon before the condition is
necessary.

16
Option 3: The infinite loop
One of the most interesting uses of the for loop is the creation of the infinite loop. Since none of the three
expressions that form the for loop are required, it is possible to make an endless loop by leaving the conditional
expression empty.
For example: for (; ;)
printf(“The loop will run forever\n”);
Actually the for (; ;) construct does not necessarily create an infinite loop because C’s break statement, when
encountered anywhere inside the body of a loop, causes immediate termination of the loop.
Program control then picks up the code following the loop, as shown here:
for (; ;)
{
ch = getchar( ); /* get a character */
if (ch = = ‘A’)
break ;
}
printf (“you typed an A”);
This loop will run until A is typed at the keyboard.

break: When a break statement is enclosed inside a block or loop, the loop is immediately exited and program
continues with the next statement immediately following the loop.

 When loop are nested break only exit from the inner loop containing it.
The format of the break statement is:

Example : Program to demonstrate break statement.


#include<stdio.h>
void main()
{
int i=1;
while(i<=10)
{
if(i==8)
break;
printf(“%d\t”,i);
i=i+1;
}
17
printf(“\n Thanking You”);
}

Continue: When a continue statement is enclosed inside a block or loop, the loop is to be continued with the next
iteration.

 The continue statement tells the compiler, skip the following statements and continue with the next iteration.
 The format of the continue statement is:

Example : Program to demonstrate continue statement.


#include<stdio.h>
void main()
{
int i;
for(i=1;i<=5;i++)
{
if(i == 3)
{
i=i+1;
continue;
}
printf(" %d\n",i);
}
}

18
ARRAYS
ARRAY: An array is a fixed-size sequenced collection of elements of same type.

 To process large amount of data, C uses a powerful data structure called array.
 An array is a collection of elements of the same data type.
 Array elements can be initialized, accessed and manipulated using the indexing.
Example:
int score[10] :
Here score will contain 10-elements
 Array index always start at ‘0’ and end at total-number of elements minus one.
 In our example the index for score will start at 0 and end at 9.
Using Arrays in C
C provides two different types of arrays
 One-Dimensional arrays.
 Two-Dimensional arrays.
In One-dimensional arrays the data are organized linearly in only one direction.
In Two-Dimensional arrays the data are organized in rows and columns, like a matrix.

ONE-DIMENSIONAL ARRAYS:
Array declaration and definition
 Like every other object in C, an array must be declared, defined and initialized before it can be used in the
program.
 Array declaration tells the compiler the name of the array.
 Array definition specifies the size or number of elements in the array. In a fixed length array, the size of the
array is a constant and must have a value at the compile time.
Example: type arrayname[array_size];

19
 The declaration and definition format for a variable length is same as like a fixed length array except the
size is a variable. The array size will be determined when the program is executed. Once the size is
determined it cannot be changed.

Accessing elements in arrays:


 To access the individual elements in an array the array index can be used. The index must be an integral
value or can be an expression that evaluates to an integral value.
 To process all the elements in the array a loop can be used. Consider the following code segment:
for(i=0;i<10;i++)
printf(“ %d”, scores[i]);
 The arrays name is the symbolic reference for the address to the first byte of the array. The index represents
an offset from the beginning of the array to the element being referenced.

Storing values in Arrays:


 Declaration and definition only reserves space for the elements in the array.
 To store values in the array they must be initialized.
 To initialize values in the array elements they can be read from the keyboard or they can be assigned with
individual values.

Initialization:
 Array elements in a fixed-length array can be initialized when they are declared. For variable-length arrays
they cannot be initialized when they are defined.
 To initialize the array elements with a set of values, they must be enclosed in braces and separated by
commas.
 It is a compile error to specify more values than elements in the array.
 The initialization can be done in the following ways:
(a) Basic initialization: int scores[5]={3,7,12,24,45};
(b) Initialization without size: int scores[]={3,7,12,24,45};
(c) Partial initialization: int scores[5]={3,7,0,0,0};
(d) Initialization to all zeros: int scores[5]={0};
The first example array the score array will have 5-elements and they contain specific set of
values.
In the second example, when the array is completely initializing then the size attribute can be
omitted.
In the third example, if the array is initialized with partial values rest of the elements will be
initialized to zero.
In the fourth example can be used to initialize all the elements to zeros.

Inputting values:
 An array can be initialized from the keyboard. The values can be read from the keyboard and initialized to
array.
 The most appropriate loop to use with arrays is the for loop.
for(i=0;i<9;i++)
scanf(“%d”,&scores[i]);
Assigning values:
20
 Array elements can be assigned individually by using a set of values, with the help of assignment operator.
Example: scores[4]=10;
 Assigning one array to another array is not possible even if they match fully in type and size. To do so we
have to copy all the elements individually from one array to another.
for(i=0;i<10;i++)
scores[i]=temp[i];
Printing values:
 To print the contents of the array, a normal for loop can be used.
Example: for(i=0;i<10;i++)
printf(“%d “,scores[i]);

Index Range checking:


 The C-language does not check the boundary of an array.
 As a programmer it is our job to ensure all references to indexed elements are valid and within the range.
 If an array is used with an invalid index, the results will be unpredictable.
Example: for(i=1;i<=10;i++) // indexing going out of range
printf(“%d “,scores[i]);

Accessing elements of one dimensional array:


 You know how to declare and initialize an array. Now lets understand, how to access an array elements.
 To access an array element use name of the array with the subscript in brackets.
 Suppose you have an array called temperature, for storing temperature in a year.
 Then the subscripts would be 0,1,…,364.
 For example to access temperature of fifth day:
temperature [4]

 To assign or store the value 89 for the 150th day:


temperature [149] = 89;
 You can loop through the elements of an array by varying the subscript.
 To set all of the values to 0, say
for(i = 0;i < 365; i++)
temperature[i] = 0;
 You can not use assignment statement directly with arrays.
 If a[] , b[] are two arrays then the assignment a=b is not valid.
 C does not provide array bounds checking.
 Hence, if you have
double stockPrice[5];
printf ("%d", stockPrice[10]);
 This will compile, but you have overstepped the bounds of your array.
 You may therefore get wrong value.

21
//Program to calculate sum of all the array elements.
#include <stdio.h>
void main()
{
int a[10];
int i, size, total=0;
printf("\n Enter the size of the array : ");
scanf("%d", &size);
printf("\n Enter the elements of an array : ");
for (i = 0; i < size ; i++)
scanf("%d",&a[i]);
for (i = 0; i < size ; i++)
total += a[i];
printf(“Sum of all array elements: %d", total);
}
TWO-DIMENSIONAL ARRAYS
 In One-dimensional arrays the data are organized linearly in only one direction.
 Many applications require data to be stored in more than one dimension.
 Matrices require an array that consists of rows and columns as shown in the following figure, which is
generally called as two-dimensional array.

 In C-language a two dimensional array will be considered as an array of arrays. That is a two dimensional
array is an array of one-dimensional arrays.

Declaration:
 Two-dimensional arrays like One-dimensional arrays must be declared and defined before being used.
 Declaration tells the compiler the name of the array; definition specifies the type and size of each
dimension.
 The size of a two array must be a constant and must have a value at compile time.
Example: int scores[5][4];

Initialization:
 The definition of a Two-Dimensional array only reserves the memory for the elements in the array.
 No values will be stored in the locations. The locations will generally contain unpredictable values or
garbage values without initialization.

22
 Initialization of array can be done when the array is defined.
 The values for the array must be enclosed in braces.
Example: int scores[3][2]={2,3,5,4,6,9};
 Nested braces must be used to show the exact number of rows and columns.
Example: int scores[3][2]={{2,3,5},{4,6,9}};
 In a Two-Dimensional array, if the array is completely initialized with values, only the first dimension can
be omitted. The second dimension must need to be specified.
Example: int scores[][2]={{2,3,5},{4,6,9}};
 The whole array can be initialized to zeros.
Example: int scores[5][4]={0};

Inputting Values:
 Another way to initialize the values is, we can read them from the keyboard.
 In Two-Dimensional array, it usually requires nested for loops.
 The first loop, the outer loop controls the rows from zero to the maximum number and the inner loop
controls the columns from zero to the maximum number.
Example: for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf(“%d”,&scores[i][j]);
Outputting values:
 The values inside a Two-Dimensional array can be printed using two nested loops.
 The first loop, the outer loop controls the rows from zero to the maximum number and the inner loop
controls the columns from zero to the maximum number.
 To print the matrix in a table format, a newline is printed at the end of each row.
Example: for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“ %d”,scores[i][j]);
printf(“\n”);
}
Accessing values:
 Individual elements can be initialized using the assignment operator.
scores[2][0]=23;
scores[2][2]=scores[1][1]+12;

/* Write a C program to perform Addition of two matrices */


#include <stdio.h>
#include <conio.h>
int main()
{
int a[10][10], b[10][10], result[10][10], r,c ,i, j, k;
clrscr();
printf("Enter rows and column for matrices: ");
scanf("%d %d", &r, &c);
// Storing elements of first matrix.
23
printf("\nEnter elements of matrix 1:\n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter elements a[%d][%d]: ",i, j);
scanf("%d", &a[i][j]);
}
// Storing elements of second matrix.
printf("\nEnter elements of matrix 2:\n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter elements b[%d][%d]: ",i, j);
scanf("%d",&b[i][j]);
}
// Adding matrices a and b and
// storing result in result matrix

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


{
for(j=0; j<c; ++j)
{
result[i][j] = a[i][j]+b[i][j];

}
}
// Displaying the result
printf("\nMatrix 1:\n");
for(i=0; i<r; ++i)
{
for(j=0; j<c; ++j)
printf("%d ", a[i][j]);
printf("\n");
}
printf("\nMatrix 2:\n");
for(i=0; i<r; ++i)
{
for(j=0; j<c; ++j)
printf("%d ", b[i][j]);
printf("\n");
}
printf("\nOutput Matrix:\n");
for(i=0; i<r; ++i)
{
for(j=0; j<c; ++j)
printf("%d ", result[i][j]);
24
printf("\n");
}
getch();
return 0;
}

STRINGS
 A string is a series of characters treated as a single unit.
 String is a variable length piece of data. Strings are divided into two major categories.
o Fixed length strings.
o Variable length strings.

Fixed length strings:


 In implementation of a fixed-length string, the important thing is to make decide the size of the variable. If
we make it too small, it sometimes can’t store all of the data. If we make it too big, we waste the memory.
 Another problem is how to differentiate between data and non-data. A solution is to use special characters
like spaces to indicate non data. In this case the space can’t be used as a character in the string.

Variable-Length strings:
 A much preferred solution is to create a structure that can expand and contract according to the size of the
value we want to store.
 Example: To store a person name with only three characters the structure should contract and provide three
characters and to store a person name with 30-characters the structure should expand and provide 30-
characers.
 Here also there is a problem: as we are using a variable length structure in computers memory, there must be
a way to indicate the end of the string.
 Two common techniques are used to indicate the end of the string.
o Length-Controlled Strings
o Delimited Strings

Length-Controlled Strings:
 In this type of strings a count is used as the first character in the string that specifies the number of
characters in the string.
 This count then be used by string manipulation functions to determine the length of the string.

Delimited Strings:
 In this type of strings the end is specified by a special character known as delimiter, hence the name
delimited strings.
 This concept is similar to using a full stop (.) at the end of a sentence in English. Where each sentence is of
variable length and a special symbol full stop is used to indicate the end of the sentence.
 The disadvantage of using a delimiter is that it eliminates one character from being used for data in the
string.

25
 The most common delimiter is a null character (\0).
 All C strings are of variable length and delimited once.

C-Strings
 A C string is a variable length array of characters that is delimited by the null character.
 A string is stored in an array of characters and delimited by a null character (\0).

 As a string is stored in an array, the name of the string is a pointer to the beginning of the string.
 There is a big difference between how a character is stored in memory and a one-character string is stored.
The character requires only one memory location, but the one-character string requires two memory
locations one for actual character and one for delimiter.
 To store an empty string in memory also requires one memory location to store the delimiter.

String Constants:
 A string literal or a string constant is a sequence of characters enclosed in double quotes.
 When string constants are used in a program, C automatically creates an array of characters, initializes to a
null delimited string, and stores it.
Example: “C is a programming language”
“Hello World”
 A string literal is stored in memory like any other object. It has an address, and can be referred by using a
pointer. Here the string literal as it is a sequence of characters, itself a pointer constant to the first element.
 The string itself can be used to refer the individual characters by using index.
Example: “hello”[1]  e

Declaring and defining Strings:


 C has no string type. To use strings in C programming they must be declared and defined as character
arrays.
 When defining the array to a store a string, we must provide enough space for both actual data and
delimiter.
26
Example: char str[9];
 In this example it is possible to store a string of eight characters long as the last character must be a
delimiter.
 A character pointer can also be used to hold strings of variable length in a program, because the name of the
string or the string itself is a reference to the starting memory location.
Example: char* pStr;
Initializing Strings:
 Initialization of strings is much like initialization any other object in C. We use assignment operator to
initialize the string when they are defined.
Example: char str[9]=”Good day”;
 As declaration, definition and initialization all are happening at a same point of time, the size attribute can
be ignored.
Example: char str[]=”Good day”;
 Strings can be initialized by using a set of characters where the last character is going to be the delimiter.
This method is not used, because it is very tedious to code.
Example: char str[9]={‘G’,’o’,’o’,’d’,’ ‘,’D’,’a’,’y’,’\0’};
 The most common way for defining and initializing a string in programming is using a pointer. This method
first creates a string literal into the memory and assigns its address to the character pointer. Later that
pointer can be used to refer the string.
Example: char* pStr=”Good Day”;
String Input/Output functions
Functions gets() and puts() are two string functions to take string input from the user and display it respectively
#include<stdio.h>

int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}

Strings and the Assignment Operator


 The string is an array and the name of the string is a pointer constant.
 As a pointer constant is should always be used as an rvalue but not as lvalue.
Example: char str1[6]=”Hello”;
char str2[6];
str1=str2; //compile error
String Manipulation Functions:
The C Library provides a rich set of string handling functions that are placed under the header file <string.h> and
<ctype.h>.
Some of the string handling functions are (string.h):
27
strlen() strcat() strcpy()
strcmp() strstr() strrev()

Some of the string conversion functions are (ctype.h):


toupper() tolower() toascii()

All I/O functions are available in stdio.h


scanf() printf() gets() puts()
getchar() putchar()

C provides different predefined set of string functions which are helpful in manipulating the strings.

String Length
strlen () function:
 This function counts and returns the number of characters in a string. It takes the form
Syntax: int n=strlen(string);
 Where n is an integer variable, which receives the value of the length of the string. The counting ends at the
first null character.
 The string length function (strlen) returns the length of a string that is the number of characters in the string
excluding the null character.
 If the string is empty then the string length function returns zero.

String Copy
 The String copy functions strcpy(); copies the contents from one string including the null character to
another string.
 There are two string copy functions:
I. Basic string copy strcpy();
II. String copy length controlled strncpy();
I. Basic string copy strcpy();
 The basic string copy function strcpy(); copies the contents of the from one string fromstr including
the null character to another string tostr.
Syntax: strcpy(string1,string2);
 If fromstr is longer than the tostr then, the data in memory after tostr is destroyed.
 The destination string should be large enough to hold the source string.
 If fromstr is longer than tostr, the data in memory after tostr is destroyed.
 The function returns the address of tostr.
28
II. String copy length controlled strncpy();
 String copy length controlled strncpy(); function copies the content of one sting to another, but it sets
a maximum number of characters that are to be copied.
 This function contains a parameter that specifies the maximum number of characters that can be
copied at a time.
Syntax: strncpy(string1,string2,size);
 If the actual size of the fromstr is equal or greater than size parameter, then size number of characters
are copied.
 If the fromstr size is smaller than the size parameter, the entire string is copied and then null
characters are inserted into the tostr until the size parameter is satisfied.
 If the fromstr is longer than the size the copy stops after size bytes have been copied. In this case the
destination variable tostr may not be a valid string; that is it may not have a delimiter.

Sring Compare
C has two string compare functions:
I. Basic string compare strcmp();
II. String compare length controlled strncmp();

I. Basic string compare strcmp();


 The strcmp(); function compares the two string until an unequal character is found or until the end of the
string is reached.
 This function returns an integer to indicate the result of the comparison.
Syntax: strcmp(str1,str2);
 If both strings are equal the function returns zero.If length of str1 < str2, it returns < 0 value. If length of str1
> str2, it returns > 0 value.

II. String comparison length controlled strncmp();


 The strncmp(); function compares the two strings until unequal character is found in a specified number of
characters have been tested, or until the end of the string is reached.
 This function returns an integer to indicate the result of the comparison.
Syntax: int strncmp(str1, str2, size);
 If both strings are equal the function returns zero. If length of str1 < str2, it returns < 0 value. If length of
str1 > str2, it returns > 0 value.
#include <stdio.h>
#include <string.h>
void main( )
{
char str1[ ] = "Hyderabad" ;
char str2[ ] = "Hydarabad" ;
int i, j, k;
29
i = strncmp ( str1, str2, 3) ;
j = strncmp ( str1, str2, 4) ;
k = strncmp ( str1, str2, 10) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
Output
0 4 4

String Concatenation
 The string concatenation function appends one string to the end of another string.
 The size of the destination string should be large enough to hold the resulting string. If it is not the data at
the end of the destination string will be destroyed.
 C has two string concatenation functions:
I. Basic string concatenation strcat();
II. String concatenation length controlled strncat();
I. Basic string concatenation strcat();
 The function copies str2 to the end of str1, beginning at the delimiter. That is the delimiter is replaced with
the first character of the str2. The delimiter from str2 is copied to the resulting string.
Syntax: strcat(str1, str2);
 The resulting string length is the sum of the length of str1 plus the length of str2.
 The function returns the address pointers to the resulting string.
#include <stdio.h>
#include <string.h>
void main( )
{
char str1[ ] = "Hyderabad" ;
char str2[ ] = "ISL" ;
strcat ( str1, str2) ;
printf ( "%s", str1 ) ;
}
Output
HyderabadISL

II. String concatenation length controlled strncat();


 The strncat(); function copies only the specified number of characters from source string str1 to
destination string str2. A null character is appended at the end.
Syntax: strncat(str1, str2, size);
 If the length of str2 is less than size, then the function will work in same as basic string copy.
 If the length of str2 is greater than size, then only the number of characters specified by size are
copied, and a null character is appended at the end.
 If the value of size is zero or less than zero, then no characters are copied.
#include <stdio.h>
30
#include <string.h>
void main( )
{
char str1[ ] = "Hyderabad" ;
char str2[ ] = "ISL" ;
strncat ( str1, str2, 2) ;
printf ( "%s", str1 ) ;
}
Output
HyderabadIS

Search for a substring


 Searching for a sub-string in a string can be done only from the beginning of the string.
 The function strstr(); is used to locate a substring in a string from the beginning of the string.
Syntax: strstr(string, sub_string);
 If sub_string exists in string then a pointer pointing to the first character of the sub_string is returned.
 If sub_string does not exist in string then a null pointer is returned.
String reverse
strrev() function:
Reverses the contents of the string.
 It takes of the form
Syntax: strrev(string);
Example:
#include<stdio.h>
#include<string.h>
void main(){
char s[]=”hello”;
strrev(s);
puts(s);
}

/*Define functions- length of a string, copy, concatenate, convert into uppercase letters, compare two strings
for alphabetical order- over strings and implement in a program*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
void main() {
char str1[15],str2[15],str3[10];
int n,c,len,i;
printf("\n Enter the string1 ");
gets(str1);
puts(str1);
printf("\n Enter the string2 ");
31
gets(str2);
puts(str2);
printf("Enter the string 3 ");
scanf("%s",str3);
printf("%s",str3);
printf("\n***************************");
printf("\n 1. String Length ");
printf("\n 2. String Copy ");
printf("\n 3. String Comparison ");
printf("\n 4. String Concat ");
printf("\n 5. UpperCase ");
printf("\n***************************");
printf("\n Enter the choice u want to perform");
scanf("%d",&n);
switch(n)
{
case 1: len=strlen(str1);
printf("\n The length of the string entered is %d",len);
break;
case 2: strcpy(str1,str2);
printf("\n 1st string =%s,2nd string=%s",str1,str2);
break;
case 3: c=strcmp(str1,str2);
if(c==0)
printf("\n Both are equal");
else
printf("\n Both are different");
break;
case 4: printf("\n The resultant string is: %s",strcat(str1,str2));
break;
case 5: for(i=0;i<strlen(str1);i++)
str1[i]=toupper(str1[i]);
printf("%s",str1);
break;
default: printf("\n Enter correct choice");
}
}

OUTPUT:
Enter the string1: abcd
abcd
Enter the string2: efgh
efgh
Enter the string3: pqr
pqr
***************************
32
1. String Length
2. String Copy
3. String Comparison
4. String Concat
5. UpperCase
***************************
Enter ur choice 4
The resultant string is: abcdefgh

33

You might also like