Arrays, Functions
Arrays, Functions
DECISION STATEMENTS:-
The if statement:-
‘C’ uses the keyword if to execute a set of command lines or one command line when the logical
condition is true. It has only one option. The sets of command lines are executed only when the logical
condition is true.
Syntax:-
if(test expression)
{
statement_block;
}
statement_x;
The statement_block may be a single statement (or) group of statements. If the test expression is true, the
statement_block will be executed; otherwise the statement_block will be skipped and the execution will
jump to the statement_x;
Flow chart of simple if:-
Entry
test True
expression
?
Statement block
False
Statement - X
Next statement
Example:- Write a program to check whether the entered number is less than 10? If yes, display the
same.
#include <stdio.h> #include <conio.h> getch();
void main() }
{ Output:-
int a; Enter number3
The given number is less
clrscr(); than 10
printf(“\n Enter number”);
scanf(“%d”,&a);
if(a<10)
printf(“\n the given number is less
than 10”);
1
if else statement:-
The if block statements execute only when the condition in ‘if’ is true. When the condition is false,
program control executes the next statement which appears after the if statement. The if-else statement
takes care of the true and false conditions. It has two blocks. One block is for ‘if’ and it is executed when
the condition is true. The other block is of else and it is executed when the condition is false. The else
statement cannot be used without if. No multiple else statements are allowed with one if.
Syntax:-
if(test expression)
{
True block statements;
}
else
{
False block statements;
}
statement-x;
If the test expression is true, then the true block statements are executed, otherwise the false block
statements are executed. In either case, true block or false block will be executed.
Flowchart:-
Entry
True False
test
expression
?
True-block False-block
statement statement
Statement - X
Example:- Write a program to find whether the given number is even or odd.
#include <stdio.h>
#include <conio.h> else
void main() {
{ printf(“%d is an odd number”,n);
int n; }
printf(“\n Enter number”); getch();
scanf(“%d”,&n); }
if(n%2==0) Output:-
{ Enter number 6
printf(“ %d is an even number”,n); 6 is an even number.
}
2
Nested if…….else:-
In this statement, a number of logical conditions are checked for executing various statements. If any
logical condition is true the compiler executes the block followed by if condition, otherwise it skips and
executes the else block. In the if-else statement the else block is executed by default after failure of
condition. In order to execute the else block depending upon certain condition we can add, repetitively, if
statements in else block. This kind of nesting will be unlimited.
Syntax:_
if(test condition1)
{
if(test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
if(test condition3)
{
statement-3;
}
else
{
statement-4;
}
}
statement-x;
If the test condition-1 is false, then it check test condition-3, if it is true then it executes statement-3
otherwise it executes statement-4. If the test condition-1 is true, then it check test condition-2, if it is true
then it executes statement-1; otherwise the statement-2 will be executed and then the control is
transferred to the statement-x.
3
Flowchart:-
Entry
Statement - X
Next Statement
X
if-else-if ladder:-
In this kind of statement, a number of logical conditions are checked for executing various statements.
Here, if the first logical condition is true the compiler executes the block followed by first if condition,
otherwise it skips that block and checks for next logical condition followed by else-if, if the condition is
true the block of statements followed by that if condition is executed. The process is continued until a
true condition is occurred or an else block is occurred. If all if conditions become false it executes the
else block. In the if-else-if ladder statement the else block we may or may not have the else block.
Syntax:-
if(condition-1)
{
statement-1;
}
else if(condition-2)
{
statement-2;
}
else if(condition-3)
{
statement-3;
}
.
.
.
5
else if(condition-n)
{
statement-n;
}
else
{
default-statement;
}
statement-x;
The conditions are evaluated from top to bottom. As soon as true condition is found, the statement
associated with it is executed and the control is transferred to statement x. When all else conditions
become false, then the final else containing the default-statement will be executed.
Flowchart:-
Entry
True False
Condition
-1
True False
Statement - 1 Condition
-2
True False
Statement - 2 Condition
-3
True False
Statement - 3 Condition
-n
Statement - n
Default
Statement
Statement - X
Next Statement
X
6
Example:- Write a program to read three integers and display the largest of three numbers using else if
ladder
#include <stdio.h>
#include <conio.h> else
void main() {
{ max=c;
int a,b,c,max; }
clrscr(); printf(“\nThe largest number
printf(“\n Enter three numbers”); is%d”,max);
scanf(“%d %d %d”,&a,&b,&c); getch();
if((a>b)&&(a>c)) }
{ Output:-
max=a; Enter three numbers 6
}
else if((b>a)&&(b>c)) 3
{ 7
max=b; The largest number is 7
}
break:-
The keyword break allows the programmers to terminate the loop. The break statement skips from the
loop or block in which it is defined. The control then automatically goes to the first statement after the
loop or block. The break statement can be associated with all conditional statements. We can also use
break statements in the nested loops. If we use break statement in the innermost loop then the control of
the program is terminated only from the innermost loop.
Example:-
Write a program to print number from 1 to 50 and terminate when the value is more than 25.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=50;i++)
{
if(i>25)
{
break;
}
printf(“\t %d”,i);
}
getch();
}
7
Output:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23 24 24
continue:-
The continue statement is exactly opposite of the break statement. The continue statement is used for
continuing the next iteration of the loop statements. When it occurs in the loop it does not terminate, but
it skips the statements after this statement. It is useful when we want to continue the program without
executing any part of the program.
Example:-
Write a program to print the even numbers from 2 to 50 by missing 8, 18, 28 number.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
clrscr();
for(i=2;i<=50;i=i+2)
{
if(i==8||i==18||i==28)
{
continue;
}
printf(“\t %d”,i);
}
getch();
}
Output:-
2 4 6 10 12 14 16 20 22 24 26 30 32 34
36 38 40 42 44 46 48 50
goto:-
This statement does not require any condition. This is an unconditional control jump. This statement
passes control anywhere in the program i.e., control is transferred to another part of the program without
testing any condition.
Syntax:-
goto label;
where, label name must start with any character. Here, the label is the position where the control is to be
transferred.
8
Example:-
Write a program to find whether the given number is even or odd. Use goto statement.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
int n;
clrscr();
printf(“\n Enter n value”);
scanf(“%d”,&n);
if(n%2==0)
{
goto even;
}
else
{
goto odd;
}
even:
printf(“\n %d is even number”,n);
odd:
printf(“\n %d is odd number”,n);
getch();
}
Output:-
Enter n value78
78 is even number.
switch statement:-
When one of the many alternatives is to be selected, using if statements can increase the complexity as
the number of alternatives increase. ‘C’ has a built in multi way decision statement known as a switch.
The switch statement tests the value of a given variable against a list of case values and when a match is
found, a block of statements associated with that case is executed. The general form of switch statement
is shown below:
switch(expression)
{
case value1:
block1;
break;
case value2:
block2;
break;
………………..
………………..
default:
9
defaultblock;
break;
}
statement-x;
The expression is an integer expression or characters. value-1, value-2 ….. are constants and are known
as case lables. block-1, block-2 …. are block of statement lists which may contain zero or more
statements.
When the switch is executed, the value of the expression is successfully compared against the values
value-1, value-2, ….
If a case is found whose value matches with the value of the expression, then the block of statements that
follow the case are executed.
Flow Chart:-
Entry
Switch
expressi
Expression = value-1
Block 1
Expression = value-2
Block 2
Statement -X
The break statement at the end of each block signal the end of a particular case and causes an exit from
the switch statement, transferring the control to the statement-x following the switch.The default is an
optional case. When present, it will be executed if the value of the expression does not match with any of
the case values. If not present, no action takes place if all the matches fail and the control goes to the
statement-x.
Advantages of switch:-
1. The switch control structure is having more readability than using if control structures.
2. The switch control structure is used mainly in menu driven programs.
3. In the switch control structures if the given expression matches with value 1 then the statements in
that case are executed and control comes to the first statement after the switch control structure due to
the presence of break statement.
10
4. If the given expression does not matches with value1 then it goes for checking value 2 and .….. value
n.
5. If no switch case is matched with the given expression then automatically statements in the default
case are executed and control comes out of the switch case.
6. The expression must be an integer expression or character expression which yields either integer
value or char value.
Programs:-
Loop Control:-
Loops:-
A loop is defined as a block of statements which are repeatedly executed for certain number of times.
There are three types of loop control elements. They are:
Initialization expression:- It sets initial value for the loop counter before the statements within the loop
body start to execute.
Test Expression:- It tests the condition to determine whether to execute the loop or not.
Update expression:- It increments or decrements the loop counter values such that after appropriate
iterations, test condition will result false and loop will be terminated.
while loop:-
The while loop is best suited to repeat a statement or a set of statements as long as some condition is
satisfied. The general form of while loop is:
while(test condition)
{
statement-block;
}
statement-x;
The test condition is indicated at the top and it tests the value of the expression before processing the
body of the loop. The test condition may be any expression. The loop statements will be executed till the
condition is true, i.e., the test condition is evaluated and if the condition is true, then the body of the loop
is executed. When the condition becomes false the execution will be out of the loop.
Test false
condition
True
Statement_block
13
Here, the block of the loop may contain either a single statement or a number of statements. The same
block can be repeated. The braces are needed only if the body of the loop contains more than one
statement.
Example:-
Write a program to print 1 to 10 numbers using while loop.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
int i=1;
clrscr();
while(i<=10)
{
printf(“\t %d”,i);
i++;
}
getch();
}
Output:-
1 2 3 4 5 6 7 8 9 10
14
Execution sequence affected by do-while construct:-
1. The statements in the body of the loop get executed once and then the control goes to the conditional-
expression.
2. The conditional-expression is evaluated first.
3. If it evaluates to true then the body of the loop is re-entered.
4. After the statements in the body of the loop get executed for the second time, the control goes back to
the conditional-expression.
5. Once again the conditional-expression is evaluated. If it evaluates to true, again the body of the loop
gets executed.
6. This process is repeated as long as the test expression evaluates to true.
7. Once the condition evaluates to false, the loop is exited and the control goes to the next statement
after the loop.
Flow chart:-
Initialization
Test
true condition
False
Example:-
Write a program to print 1 to 10 numbers using do-while loop.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
int i=1;
clrscr();
do
{
printf(“\t %d”,i);
i++;
} while(i<=10);
getch();
}
Output:-
1 2 3 4 5 6 7 8 9 10
for loop:-
15
The for loop is most common in major programming languages. However, the for loop in C language is
very flexible and very powerful. Generally, the for loop is used to repeat the execution of a statement for
some fixed number of times.
Syntax:-
for(initialization;conditional-expression;increment)
{
statement-block;
}
statement-x;
The general form of the looping construct starts with the keyword for. The keyword is followed by the
three fundamental things to construct a loop, initialization, conditional-expression and increment all in
one place, separated by semicolons and enclosed within a pair of parentheses.
False
Test
conditio
true
Statement_block
Example:-
Write a program to print 1 to 10 numbers using for loop.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
clrscr();
16
for(i=1;i<=10;i++)
{
printf(“\t %d”,i);
i++;
}
getch();
}
Output:-
1 2 3 4 5 6 7 8 9 10
17
}
Output:-
Enter n value 3
1
1 2
1 2 3
18
ARRAYS
The fundamental data types, namely char, int, float, double. ‘C’ supports a derived data type known as
array to process large amounts of data.
An array is defined to be a collection of logically related data items of same type, stored in contiguous
memory location, sharing a common name but separated by subscripts values.
An array is a homogenous collection of data items which represent the same data types.
Declaration of an array:-
Declaration of a one dimensional array can be done with data type first, followed by the variable name
and at last the size is enclosed in square brackets.
Syntax: - datatype arrayname [arraysize];
Example:- int a[5];
It tells the complier that ‘a’ is an integer type of an array and can store five integers. The complier
reserves 2 bytes of memory for each integer array element, i.e., 10 bytes are reserved for storing five
integers in the memory.
Examples:- char ch[10];
float d[10];
long n[5];
Array Initialization:-
The syntax for array initialization
datatype arrayname[arraysize]={list of values};
The values in the list are separated by commas.
Example:-
1. int a[6]={1,2,3,4,5,6};
Here, six elements are stored in an array ‘a’. The array elements are stored sequentially in separate
locations. Reading of the array elements begins from ‘0’.
a[0] a[1] a[2] a[3] a[4] a[5]
1 2 3 4 5 6
2. int a[6]={1,2,3};
If there are only three values are passed to the array of size 6, the rest of them are filled with zeros.
a[0] a[1] a[2] a[3] a[4] a[5]
1 2 3 4 5 6
19
The initialization can be done at the complier time or dynamically at the run time.
Array terminology:-
Size: - Number of elements or capacity to store elements in an array is called its size. It is always
mentioned in brackets [ ].
Type: - Types refer to data type. It decides which type of element is stored in the array. It also instructs
the compiler to reserve memory according to data type.
Base: - The address of the first element (0th) is a base address. The array name itself stores address of the
first element.
Index: - the array name is used to refer to the array element. For example, a[x], a is array name and x is
index. The value of x begins from 0 to onwards depending on the size of the array. The index value is
always an integer value.
Range: - Index of an array i.e. , value of x varies from lower bound to upper bound while writing or
reading elements from an array. For example in a[100] the range of index is 0 to 99.
Word: - It indicates the space required for an element. In each memory location, computer can store a
data piece. The space occupation varies from machine to machine. If the size of element is more than
word (one byte) then it occupies two successive memory locations. The variables of data type int, float,
long need more than one byte in memory.
Characteristics of an array:-
1. The declaration int a[5] is nothing but creation of five variables of integer types in memory. Instead
of declaring five variables for five values, the programmer can define them in an array.
2. All the elements of an array share the same name, and they are distinguished from one another with
the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the other elements.
int a[5]={1,2,3,4,5};
If a programmer needs to replace 5 with 10, then it need not require changing all other number
except 5. To carry out this task the statement a[4]=10 can be used. Here, other four elements are not
disturbed.
5. Any element of an array a[ ] can be assigned/equated to another ordinary variable or array variable of
its type.
Example:-
b=a[2];
a[2]=a[3];
a. In the statement b=a[2] or vice versa, the value of a[2] is assigned to ‘b’, where ‘b’ is an integer.
b. In the statement a[2]=a[3] or vice versa, the value of a[2] is assigned to a[3], where both the
elements are of the same array.
6. Array elements are stored in contagious memory locations.
7. Once the array is declared, its lowest boundary cannot be changed but upper boundary can be
expanded. The array name itself is a constant pointer and we cannot modify it. Therefore, the lowest
20
boundary of an array cannot be expanded. In other words, even if the boundary exceeds than
specified, nothing happens. The complier throws no errors.
8. We know that an array name itself is a pointer. Though it is a pointer, it does not need ‘*’ operator.
The brackets [ ] automatically denote that the variable is a pointer.
9. All the elements of an array share the same name, and they are distinguished from one another with
the help of the element number.
10. The amount of memory required for an array depends upon the data type and the number of
elements.
11. The operation such as insertion, deletion of an element can be done with the list but cannot be done
with an array. Once an array is created we cannot remove or insert memory location. An element can
be deleted, replaced but the memory location remains as it is.
12. When an array is declared and not initialized, it contains garbage values. If we declared an array as
static, all elements are initialized to zero. However, the values of static type data persist and remain
in the memory as long as program executes. To overcome this problem, initialize first element of an
array with zero or any number. Remaining all elements are automatically initialized to zero, provided
the initialization is done in the declaration statement of an array.
Example:-
char name[10]=”WELL DONE”;
When the compiler sees a character string, it terminates with an additional null character.
Initialization of arrays:-
datatype arrayname[arraysize]={list of values};
The values in the list are separated by commas.
Examples: -
21
int a[3]={1,2,3};
char name[5]={‘J’,’O’,’H’,’N’,’\0’};
If int a[5]={10,20}, the number of initializes may be less than the declared size. In such cases, the
remaining elements are initialized to zero, if the array type in numeric and NULL if the type of char.
Program:-
Write a program to read n values from the keyboard and print that n values.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
int n,i,a[30];
clrscr();
printf(“\n Enter n value”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\n Enter element”);
scanf(“%d”,&a[i]);
}
printf(“\n The elements are”);
for(i=0;i<n;i++)
{
printf(“\t %d”,a[i]);
}
getch();
}
Output:-
Enter n value5
Enter element4
Enter element3
Enter element8
Enter element1
Enter element23
The elements are 4 3 8 1 23
Predefined streams:-
The predefined streams are
1. stdin()
2. stdout()
3. stderr()
When C program is executed a few ‘files’ are automatically opened by the system for use by the
program. Constant FILE pointers recognize these files. Streams stdin, stdout and stderr are defined in the
standard I/O include files.
i. stdin:- The file pointer stdin identifies the standard input text and it is associated with the terminal.
All standard I/O functions perform input and do not take a FILE pointer as an argument and get their
input from stdin.
ii. stdout:- Similarly, it is used for outputting the text. It is a standard output stream.
iii. stderr:- It is an output stream in the text mode. It is a standard error stream.
1,4,7,
2,5,8,
3,6,9
1,4,4,
2,4,7,
8,8,5 };
Example:-
Write a program to demonstrate three dimensional array.
Source Code:-
#include <stdio.h>
31
#include <conio.h>
void main()
{
int a[3][3],i,j,k;
clrscr();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf(“\n Enter element”);
scanf(“%d”,&a[i][j][k]);
}
}
}
printf(“\n 3-D array \n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf(“\t%d”,a[i][j][k]);
}
printf(“\n”);
}
printf(“\n”);
}
getch();
}
Drawbacks of linear arrays:-
1. The number of elements, which are to be stored in an array, is to be known first.
2. When an array is declared, memory is allocated to it. If array is not filled completely, the vacant place
occupies memory.
3. Once the array is declared, its dimension can be changed.
Strings:-
In c language, a sequence of characters, digits and symbols enclosed within double quotation marks is
called a string. The string is always declared as character array and its elements are stored in contiguous
memory locations. In other words, in C, a string is defined as an array of characters.
Declaration and initialization of string:-
32
The syntax for declaring a string
char arrayname[arraysize];
Example:-
char ch[10];
The syntax for initialization of a string
char ch[10]={‘I’,’N’,’D’,’I’,’A’,’\0’};
(or)
char ch[10]=”INDIA”;
Each character of the string occupies 1 byte of memory. The last character is always ‘\0’. It is not
compulsory to write ‘\0’ in string. The compiler automatically puts ‘\0’ at the end of the character array
(or) string. While storing characters in a string array one should confirm if the array length is large
enough to store the given string.
ch[0] ch[1] ch[2] ch[3] ch[4] ch[5] ch[6] ch[7] ch[8] ch[9]
I N D I A \0
5001 5002 5003 5004 5005 5006 5007 5008 5009 5010
The length of the characters in “MAHARASHTRA” is 11 but in C the character array should have a
length of 12. One more character is needed at the end of string which is called a null character. The C
complier inserts the NULL (\0) character automatically at the end of the string. So, initialization of the
NULL character is not essential.
Example:-
Write a program to read the string and print that string.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char str[10];
clrscr();
printf(“\n Enter string”);
gets(str);
printf(“\n The entered string is %s”,str);
getch();
}
Output:-
Enter stringINDIA
The entered string is INDIA
33
C complier supports a large number of string handling library functions. The header file string.h is to be
initialized when ever standard library function is used.
7 strnicmp() Compares characters of two strings up to the specified length. Ignores case.
15 strncat() Appends the source string to the destination string up to a specified length.
20 strbrk() Searches the first occurrence of the character in a given string and then
displays the string starting from that character.
2. strcpy():- This function copies characters of one string into another string.
Syntax:- strcpy(destination_string , source_string);
Example:-
Write a program to copy the string using strcpy()
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char ch[20],ch1[20];
clrscr();
printf(“\n Enter string1”);
gets(ch);
strcpy(ch1,ch);
printf(“\n String is %s”,ch1);
getch();
}
Output:-
Enter string1INDIA
String is INDIA
4. strcmp():- This function can be used to compares two strings to find out whether they are same or
not.
Syntax:- strcmp(string1,string2);
After comparing the two strings strcmp() returns an integer value which may be
=0 if string1 is equal to string2
>0 if string1 is greater than string2
<0 if string1 is less than string2
strcmp() compares the ASCII values of characters, if there is mismatch in the characters while
comparing it returns the difference between the ASCII values as integer value otherwise returns zero.
Example:-
Write a program to compare two strings.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char str1[20],str2[20];
int d;
clrscr();
printf(“\n Enter string1”);
gets(str1);
printf(“\n Enter string2”);
36
gets(str2);
d=strcmp(str1,str2);
if(d==0)
puts(“Two strings are equal”);
else
puts(“Two strings are not equal”);
getch();
}
Output:-
Enter string1HELLO
Enter string2HELLO
Two strings are equal.
5. stricmp():- This function compares two strings. The characters of the strings may be in lowercase or
uppercase; the function does not discriminate between them. i.e., this function compares two strings
without case. If the strings are the same it returns to zero otherwise non zero value.
Example:-
Write a program to compares the two strings using the stricmp() function. If strings are identical
display “ The Two Strings are Identical” otherwise “The Strings are Different”.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char str1[20],str2[20];
int d;
clrscr();
printf(“\n Enter string1”);
gets(str1);
printf(“\n Enter string2”);
gets(str2);
d=stricmp(str1,str2);
if(d==0)
puts(“Two strings are Identical”);
else
puts(“The strings are Different”);
getch();
}
Output:-
Enter string1HELLO
Enter string2hello
Two strings are Identical
37
6. strrev():- This function is used to reverse the given string.
Syntax:- strrev(string);
Example:-
Write a program to print the string in reverse order.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char str[20];
clrscr();
printf(“\n Enter string”);
gets(str);
strrev(str);
printf(“\n The reverse string is %s”,str);
getch();
}
Output:-
Enter stringINDIA
The reverse string is AIDNI
7. strlwr():- This function can be used to convert any string to lowercase. When you are passing any
upper case string to this function it converts into lowercase.
Syntax:- strlwr(string);
Example:-
Write a program to convert the uppercase string to lowercase using strlwr().
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char str[20];
clrscr();
printf(“\n Enter the string in upper case”);
gets(str);
printf(“\n The string is %s”,strlwr(str));
getch();
}
Output:-
Enter stringINDIA
The string is india
Sn functions Description
o
4 double strtod(char *, char *) Separates char and float data from the given string
5 long strtol(char *, char *) Separates char and long int data from the given string.
Memory functions:-
Memory functions are used with the header file string.h
39
2 memove() Moves a specified range of char from one place to another
Application of strings:-
Example 1 :-
Write a program to verify the given string is palindrome or not using built-in functions.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char str[10],str1[10];
int x;
clrscr();
printf(“\n Enter string”);
gets(str);
strcpy(str1,str);
strrev(str);
x=strcmp(str,str1);
if(x==0)
printf(“%s is palindrome”,str1);
else
printf(“%s is not palindrome”,str1);
getch();
}
Output:-
Enter stringMADAM
MADAM is palindrome.
Example 2 :-
Write a program to verify the given string is palindrome or not without using built-in functions.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char str[10],str1[10];
int len=0,j=0,i,c=0;
clrscr();
40
printf(“\n Enter string”);
gets(str);
for(i=0;str[i]!=’\0’;i++)
len++;
printf(“\n The length of the given string is %d”,len);
for(i=len-1;i>=0;i--)
{
rev[j]=str[i];
j++;
}
rev[j]=’\0’;
printf(“\n The reverse string is %s”,rev);
for(i=0;i<len;i++)
{
if(str[i]!=rev[i])
{
c=1;
}
}
if(c==1)
printf(“%s is palindrome”,str);
else
printf(“%s is not palindrome”,str);
getch();
}
Output:-
Enter stringMADAM
The length of the given string is5
MADAM is palindrome.
Example 3 :-
Write a program to concatenate two strings using arrays.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char str1[10],str2[10];
int s1=0,s2=0,i,j=0;
clrscr();
printf(“\n Enter string1”);
gets(str1);
printf(“\n Enter string2”);
41
gets(str2);
for(i=0;str1[i]!=’\0’;i++)
s1++;
for(i=0;str2[i]!=’\0’;i++)
s2++;
printf(“\n The length of the string1 is %d”,s1);
printf(“\n The length of the string2 is %d”,s2);
for(i=s1;i<s1+s2;i++)
{
str2[i]=str1[j];
j++;
}
puts(str2);
puts(str1);
getch();
}
Output:-
Enter string1HELLO
Enter string2WORLD
The length of the string1 is 5
The length of the string2 is 5
HELLOWORLD
WORLD
42
Double (or) Two dimensional character arrays:-
These are similar to double dimensional array of integers. The difference is character arrays stores
strings. In a single dimensional character array only one string can be stored. To store more than one
string in a character array then it should be declared as double dimensional character array.
The syntax is
datatype arrayname[n][m];
Where n specifies number of rows.
M specifies number of columns
Example:-
Char names[6][5];
0 1 2 3 4 5
r a j u \0
s a i \0
r a n i \0
s i t a \0
a l i \0
flushall():-
flushall clear any data in stream. It doesn’t mean data gets lost, instead all buffered data process and sent
to target output source flushall function flushes all streams.
Example:-
43
Write a program to read n names into two dimensional array.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char name[10][10];
int n,i;
clrscr();
printf(“\n Enter n value”);
scanf(“%d”,&n);
flushall();
for(i=0;i<n;i++)
{
printf(“\n Enter name”);
gets(name[i]);
}
printf(“\n The names are\n”);
for(i=0;i<n;i++)
{
puts(name[i]);
}
getch();
}
Output:-
Enter n value4
Enter namesai
Enter namesiva
Enter nameram
Enter namesita
The names are
sai
siva
ram
sita
Example:-
Write a program to print the given strings in ascending order.
Source Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
char name[10][10],temp[10];
44
int n,i,j,x;
clrscr();
printf(“\n Enter n value”);
scanf(“%d”,&n);
flushall();
for(i=0;i<n;i++)
{
printf(“\n Enter name”);
gets(name[i]);
}
printf(“\n The names before sorting are\n”);
for(i=0;i<n;i++)
{
puts(name[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
x=strcmp(name[j],name[j+1]);
if(x>0)
{
strcpy(temp,name[j]);
strcpy(name[j],name[j+1]);
strcpy(name[j+1],temp);
}
}
}
printf(“\n The names after sorting are”);
for(i=0;i<n;i++)
{
puts(name[i]);
}
getch();
}
Output:-
Enter n value4
Enter namesai
Enter namesiva
Enter nameram
Enter namesita
The names before sorting are
sai
45
siva
ram
sita
The names after sorting are
ram
sai
sita
siva
46