0% found this document useful (0 votes)
266 views36 pages

Unit - Ii Decision Making, Branching, Looping Arrays & Strings

This document discusses various control structures in C programming, including conditional statements, looping statements, and arrays and strings. 1. Conditional statements include if-else statements, switch statements, and nested if-else statements that allow a program to make decisions and execute different blocks of code conditionally. 2. Looping statements like while, do-while and for are used to repeatedly execute a block of code until a certain condition is met. 3. Arrays allow grouping of multiple variables of the same type under one name, while strings are arrays of characters that represent text data. Control structures are essential for writing complex programs that can handle different conditions and scenarios.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
266 views36 pages

Unit - Ii Decision Making, Branching, Looping Arrays & Strings

This document discusses various control structures in C programming, including conditional statements, looping statements, and arrays and strings. 1. Conditional statements include if-else statements, switch statements, and nested if-else statements that allow a program to make decisions and execute different blocks of code conditionally. 2. Looping statements like while, do-while and for are used to repeatedly execute a block of code until a certain condition is met. 3. Arrays allow grouping of multiple variables of the same type under one name, while strings are arrays of characters that represent text data. Control structures are essential for writing complex programs that can handle different conditions and scenarios.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 36

UNIT – II

Decision Making, Branching, Looping Arrays & Strings

CONTROL STRUCTURES (OR) CONTROL STATEMENTS:

Control statements are the statements which Alter the flow of execution and provide better
control to the programmer. They are useful to write better and complex programs.
Control structures are classified into three types.
1. Conditional statements or decision making statements or selection statements
2. Looping statements or Iterative statements
3. Un conditional statements or jump statements

1. CONDITIONAL STATEMENTS OR DECISION MAKING STATEMENTS OR SELECTION


STATEMENTS
conditional statements are used to execute one or more statements based on condition. There are
mainly three types of conditional statements. They are
a. if statement
b. switch statement

a. The if Statement
It is used to execute an instruction or sequence/block of instruction only if a condition is true.
Difference forms of implements if-statement are:

 Simple if statement
 if-else statement

 Nested if-else statement

 else if statement

i. Simple if statement

 it is used to execute one or more statements based on execution .


1
 Operation: whenever condition is true control enters into the if block and executes all
the statements and continue execution of remaining statements of program.
 Whenever condition is false if block statements will be neglected or skipped and
remaining statements will be executed.
 syntax and flowchart

Example1: /*Demonstration of if statement */


#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}
Output:

Variable x is less than y


Explanation: The condition (x<y) specified in the “if” returns true for the value of x and y, so
the statement inside the body of if is executed.

Example2

Example of multiple if statements

We can use multiple if statements to check more than one conditions.

#include <stdio.h>
int main()
{
int x, y;

2
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");
scanf("%d", &y);
if (x>y)
{
printf("x is greater than y\n");
}
if (x<y)
{
printf("x is less than y\n");
}
if (x==y)
{
printf("x is equal to y\n");
}
printf("End of Program");
return 0;
}
In the above example the output depends on the user input.

Output:

enter the value of x:20


enter the value of y:20
x is equal to y
End of Program

ii. If-else statement: This statement is used to execute one or more statements based
on conditions. If-else statement mainly used to select one option among two options.
Operation: whenever condition is true if block statements will be executed by neglecting
else block statements and execute all the statements after the else block statements.
Syntax and flowchart

3
Example : /*Demonstration of if-else statement */
#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible for voting");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
printf("You are not eligible for voting");
}
return 0;
}
Output:

Enter your age:14


You are not eligible for voting
Note: If there is only one statement is present in the “if” or “else” body then you do not need to
use the braces (parenthesis). For example the above program can be rewritten like this:

#include <stdio.h>
int main()
4
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
printf("You are eligible for voting");
else
printf("You are not eligible for voting");
return 0;
}

iii.Nested if-else statement


In nested if...else statement, an entire if...else construct is written within either the body of the if
statement or the body of an else statement.
The syntax is as follows:
if(condition_1)
{
 if(condition_2)
 {
   block statement_1;
 }
 else
 {
   block statement_2;
 }
}
else
{
  block statement_3;
} Figure: nested if-else statement flowchart
block statement_4;

5
Example program:

#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 != var2)
{
printf("var1 is not equal to var2\n");
//Nested if else
if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:

Input the value of var1:12


Input the value of var2:21
var1 is not equal to var2
var2 is greater than var1

iv.Else if statement
It is used in multi-way decision on several conditions.
Operation: if first condition is true, if block statements will be executed by
neglecting remaining conditions. if first condition is false it will check
second condition if it is true corresponding if block statements will be
executed, otherwise check it will check another condition.
The else...if syntax is as follows:
if(condition_1)   block statement_1;

6
else if(condition_2)
  block statement_2;
else if(condition_n)
  block statement_n;
else
  default statement;

Figure: flowchart for else...if statement

Example1: /*program to print the grade of a student */


#include<stdio.h>
main()
{
int marks;
printf(“Enter marks”);
scanf(“%d”,&marks);
if(marks>=75)
printf(”Distinction”);
else if(marks>=60)
printf(“First Class”);
else if(marks>=50)
printf(“Second Class”);
else if(marks>=35)
printf(“Third Class”);
else
printf(“Failed”);
}

7
Example2:
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2\n");
}
else if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else if (var2 > var1)
{
printf("var2 is greater than var1\n");
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:

Input the value of var1:12


Input the value of var2:21
var1 is not equal to var2

b. THE SWITCH STATEMENT

Switch statement is also similar to else if statement. Switch statement is used


to execute one or more statements based on choice. Switch statement can be
used to select one option among multiple options
Syntax: switch(choice)
{
case value-1:
block-1;
break;
case value-2:
block-2;
8
break;
--------
--------
default:
default block;
break;
}
statement–x;
 Choice can be any integer or character value.
 Case is a keyword represents container which is a collection of
statements
 Break is a keyword represents temporary termination. Whenever it is
reached control will comes outside the switch block.
 Default is a keyword represents special container with collection of
statements.

Example: Perform arithmetic operations using switch

main()

{ switch(ch)

char ch; {

int a,b,c; case '+': c= a+b;

printf("enter a,b values"); printf("%d",c);

scanf("%d%d",&a,&b); break;

fflush(stdin); case '-': c=a-b;

printf("enter character"); printf("%d",c);

scanf("%c",&ch); break;
9
case '*': c=a*b; break;

printf("%d",c); }

break; getch();

case '/': c=a/b; }

printf("%d",c);

2. LOOPING STATEMENTS:
Sometimes we require a set of statements to be executed repeatedly until a
condition is met. C supports three looping statements. They are while, do-
while and for.
Both while and for statements are called as entry-controlled loops because
they evaluate the expression and based on the value of the expression they
transfer the control of the program to a particular set of statements.
Do-while is an example of exit-controlled loop as the body of the loop will
be executed once and then the expression is evaluated. If it is non-zero value
then the body of the loop will be executed once again until the expression's
value becomes zero.
WHILE LOOP: This is an entry controlled looping statement. It is used to
repeat a block of statements until the expression evaluates to nonzero value.
Syntax:
while(test condition)
{
body of the loop
}
Flowchart:

10
It is an entry controlled loop. The condition is evaluated and if it is true then
body of loop is executed. After execution of body the condition is once again
evaluated and if it is true body is executed once again. This goes on until test
condition becomes false.
Example: /* sum of 1 to 10 numbers */
#include<stdio.h>
main()
{
inti=1, sum=0;
while(i<=10)
{
sum=sum+i;
i=i+1;
}
printf(“Total : %d”,sum);

DO WHILE LOOP: This is an exit controlled looping statement.


Sometimes, there is need to execute a block of statements first then to check
condition. At that time such type of a loop is used. In this, block of
statements are executed first and then condition is checked.
Syntax:
do
{
statements;
(increment/decrement);
} while (expression);
Flow Chart:

11
In above syntax, first the block of statements is executed. At the end of loop,
while statement is executed. If the expression is evaluated to nonzero value
then program control goes to evaluate the body of a loop once again. This
process continues till expression evaluates to a zero. When it evaluates to
zero, then the loop terminates.
Example: /* display the numbers from 1 to 100*/
#include<stdio.h>
main()
{
Int i=1, sum=0;
do
{
sum=sum+i;
i=i+1;
} while(i<=10);
printf(“Total : %d”,sum);
}
FOR LOOP: This is an entry controlled looping statement. In this loop
structure, more than one variable can be initialized. One of the most
important features of this loop is that the three actions can be taken at a time
like variable initialization, condition checking and increment/decrement. The
for loop can be more concise and flexible than that of while and do-while
loops.
Syntax:
for(initialization; test-condition; increment/decrement)
{
statements;
}
Flow Chart:

12
In above syntax, the condition is checked first. If it is true, then the program
control flow goes inside the loop and executes the block of statements
associated with it. At the end of loop increment or decrement is done to
change in variable value. This process continues until test condition satisfies.

EX:

#include<stdio.h>
main()
{
Int i, sum=0;
For(i=1;i<+10;i++)
{
sum=sum+i;
}
printf(“Total : %d”,sum);

3. UN CONDITIONAL STATEMENTS OR JUMP STATEMENTS

BREAK STATEMENT:

This is a simple statement. C break statement is used to terminate any type of


loop such as while loop, do while loop and for loop. C break statement
terminates the loop body immediately and passes control to the next
statement after the loop.
Syntax: if(condition)
13
{
break;
}
Example: #include<stdio.h>
main()
{
Int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==7)
{
break;
}
printf(“%d”,i);
}
getch();
}

OUTPUT:1 2 3 4 5 6

CONTINUE STATEMENT:

This statement has only a limited number of uses. The rules for its use are the
same as for break, with the exception that it doesn't apply to switch
statements.C continue statement is used to skip over the rest of the current
iteration. After continue statement, the control returns to the top of the loop.
The use of continue is largely restricted to the top of loops, where a decision
has to be made whether or not to execute the rest of the body of the loop.

continue statement is associated with if statement.


Syntax: if(condition)
14
{
continue;
}
Example: #include<stdio.h>
main()
{
Int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i%2!=0)
{
continue;
}
printf(“%d”,i);
}
getch();
}
Output: 2 4 6 8 10
GOTO STATEMENT:
A goto statement is used to branch (transfer control) to another location in a
program.
Syntax: goto label;
The label can be any valid identifier name and it should be included in the
program followed by a colon.The name of the label is only visible inside its
own function; you can't jump from one function to another one.
Program: #include<stdio.h>
main()
{
int a,b;
clrscr();
15
printf(“Enter two numbers :”);
scanf(“%d%d”,&a,&b);
if(a>b)
goto largnumb;
if(a<b)
goto smallnumb;
largnumb:printf(“a is largest number”);
return;
smallnumb:printf(“a is smallest mumber ”);
}

Exit():

The function exit() will terminate the program that calls the exit.

Ex:

#include <stdio.h>

#include <stdlib.h>

main ()
{
printf("Start of the program....\n");

printf("Exiting the program....\n");


exit(0);
printf("End of the program....\n");
}
o/p: Start of the program....
Exiting the program..

ARRAYS
An array is a group of related data items that share a common name and
stored in contiguous memory locations. Ordinary variables are capable of
16
holding only one value at a time. However, there are situations in which we
would want to store more than one value at a time in a single variable.

In C, arrays are classified into two types. They are

1. One dimensional arrays

3. Multi-dimensional arrays

1. ONE DIMENSIONAL ARRAYS

One dimensional array Declaration:


Like any other variable, arrays must be declared before they are used. The
general form of array declaration is
datatype variable-name [size];
The type specifies the type of element that will be contained in the array,
such as int, float or char. Size indicates the maximum number of elements
that can be stored inside the array.
For example
1) int number[5]; Declares an array number which can store a maximum of
5 integer numbers.
2) float height[50]; Declares an array height which can store a maximum of
50 floating-point numbers.
3) char name[10]; Declares an array name which can store a maximum of
10 characters.
If we want to represent a set of five numbers say (35, 40, 20, 57, 19) by an
array variable num, then we may declare the variable num as follows.
int num [5];
And the computer reserves five storage locations as shown below. We know
that memory is group of memory cells. Each cell can store one byte of
information and each cell is accompanied with some address.

17
The values to the array elements can be assigned as follows.
num[0]=35;
num[1]=40;
num[2]=20;
num[3]=57;
num[4]=19;
This would cause the array number to store the values as shown below.

INITIALIZING ONE DIMENSIONAL ARRAYS

While declaring an array, we can initialize it with some values. The


general format to initialize one dimensional array is as follows

Syntax: datatye arrayname[size]={v0,v1,v2,-------vn}

Here, v0,v1-----vn are the initial values of the specified array. If we


omit the values then an array contains garbage values. The number of values
must be less than or equal to the size of the array. When there are few values
then the remaining elements are assigned with zeros.

We have four options for initializing one dimensional arrays.

Option 1: Initializing all memory locations

18
int temp [5] = {75, 79, 82, 70, 68};

Option 2: initialization without size (Unsized one dimensional arrays)

int temp [] = {75, 79, 82, 70, 68};

Option 3: Partial Array Initialization

int temp [5] = {75, 79, 82};

Option 4 If you do not know any data ahead of time, but you want to
initialize

19
everything to 0, just use 0 within { }.

For example:

int temp [5] = {0};

REFERENCING/ACCESSING ONE DIMENSIONAL ARRAY


ELEMENTS

A specific element in an array is accessed by an


index(subscript or dimension).The array index starts from 0 i.e ,the
first element in the array is numbered 0 and the last element is 1 less than
the size of the array. The amount of memory required to hold an array
is directly related to its type and size.

Each subscript must be expressed as non-negative integer. The


subscript values must be enclosed within square brackets. The subscript
values can be constant, variable or an expression.

Example: The ‘n’ elements of an array ‘num’ can be accessed as


Follows

num[0], num[1], num[2],------------,num[n-1] Or

The above values can be read using a loo variable as follows

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

scanf(“%d”,&num[i]);

20
1./*program to create a single dimensional array & find sum of the
elements*/
#include<stdio.h>
#include <conio.h>
void main()
{
int a[10],i,n,sum;
clrscr();
printf("enter size" );
scanf("%d",&n);
sum=0;
for (i=0;i<n;i++)
{
printf("enter array element ");
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("the array elements are\n");
for (i=0;i<n;i++)
printf("%d\n",a[i]);
printf("the sum = %d\n",sum);
getch();
}
2./*program to create a single dimensional array and to find large and
small of the array elements */
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],i,n,large,small;
clrscr();
21
printf("enter size" );
scanf("%d",&n);
for (i=0;i<n;i++)
{
printf("enter array element ");
scanf("%d",&a[i]);
}
large=a[0];
small=a[0];
for (i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("array elements are\n");
for (i=0;i<n;i++)
printf("%d\n",a[i]);
printf("largest = %d\n",large);
printf("smallest = %d\n",small);
getch();
}

3./* Program To arrange the elements in sorted order */


#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],i,j,n,temp;
clrscr();
printf("enter size" );
22
scanf("%d",&n);
for (i=0;i<n;i++)
{
printf("enter array element ");
scanf("%d",&a[i]);
}
for (i=0;i<n-1;i++)
for (j=0;j<n-i-1;j++)
if (a[j] > a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("the sorted array elements are\n");
for (i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}

MULTI-DIMENSIONAL ARRAYS

An array which has more than one dimension is called a


“multidimensional array”. Multi-dimensional arrays are classified as two
dimensional, three-dimensional, and four-dimensional and so on.

TWO DIMENSIONAL ARRAYS

When an array uses only two subscripts then it is called ”Two


dimensional”. A two-dimensional array is an array of one-dimensional
arrays. It can be viewed as table of elements which contains rows and
columns. A two-dimensional array is useful for matrix operations.

23
DECLARATION OF TWO DIMENSIONAL ARRAYS

The general format of declaring a two dimensional array is as follows

dataType arrayName [rowsize][columnsize];

In the above syntax

The data type is any valid data type of C language.

The ‘array name’ is an identifier that specifies name of the array


variable. All the elements will share this variable name.

The ‘row size’ indicates maximum number of rows and ‘column size’
indicates number of columns in a row.

Example:

int a[4][3];

Two-dimensional arrays are stored in memory as shown below.

INITIALIZING TWO DIMENSIONAL ARRAYS:


Like the one-dimensional arrays, two-dimensional arrays may be initialized
by following their declaration with a list of initial values enclosed in braces.
int num [2][3] = {0, 0, 0, 1, 1, 1};

24
This declaration initiates the elements of first row to zero and second row to
1. The Initialization is done row by row. The above statement is equivalently
written as
int num [2][3] = {{0,0,0}, {1,1,1}};
By surrounding the elements of each row by braces we can also initialize a
two-dimensional array in the form of a matrix.
int num [2][3] = {
{0,0,0},
{1,1,1}
};
If the values are missing in an initializer, they are automatically set to zero.
For instance the statement
int num[2][3] = {
{1,1},
{2}
};
will initialize the first two elements of the first row to one, the first element
of the second row to two. And all other elements to zero. Memory map of a
two dimensional array:
int num[2][3] = {1,2,3,4,5,6};

1./*program to create a two dimensional array of size mxn and print it


in matrix form */
#include<stdio.h>
#include <conio.h>
void main()
{
int a[5][5],m,n,i,j;
clrscr();
25
printf("enter a size of the array:" );
scanf("%d%d",&m,&n);
printf("enter the elements of two dimensional array\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("The two dimensional array\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
getch();
}
2. /* program to add two matrices */
#include<stdio.h>
#include <conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,i,j;
clrscr();
printf("enter a size of the array :" );
scanf("%d%d",&m,&n);
printf("enter the elements of matrix A\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("enter the elements of matrix B\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
26
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("The two dimensional array\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",c[i][j]);
printf("\n");
}
getch();
}
enter a size of the array :2 2                                                                                                 
enter the elements of matrix A                                                                                             
    
1 0 0 1                                                                                                                        
enter the elements of matrix B                                                                                             
    
1 0 0 1                  
The two dimensional array                                                                                                  
    
2 0                                                                                                                            
0 2    

3.program to multiply two matrices matrix A of size M XN matrix B of


size P XQ Resultant matrix of size M x Q
#include<stdio.h>
#include <conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
clrscr();
printf("enter a size of the array A:" );
scanf("%d%d",&m,&n);
printf("enter the elements of matrix A\n");
27
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("enter a size of the array B:" );
scanf("%d%d",&p,&q);
printf("enter the elements of matrix B\n");
for (i=0;i<p;i++)
for (j=0;j<q;j++)
scanf("%d",&b[i][j]);
if (n==p)
{
for (i=0;i<m;i++) /*initialisation of C*/
for (j=0;j<q;j++)
c[i][j]=0;
for (i=0;i<m;i++)
for (j=0;j<n;j++)
for (k=0;k<q;k++)
c[i][k]=c[i][k]+a[i][j]*b[j][k];
printf("The Resultant array\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d ",c[i][j]);
printf("\n");
}
}
else
printf("Matrix multiplication is not possible\n");
getch();
}

28
STRINGS
 C Strings are nothing but array of characters ended with null
character (‘\0’).
 This null character indicates the end of the string.
 Strings are always enclosed by double quotes. Whereas, character is
enclosed by single quotes in C.

Declaration of strings

Strings are declared in C in similar manner as arrays. Only difference


is that, strings are of char type.

char s[5];

29
Initialization of strings

In C, string can be initialized in different number of ways.

char c[]="abcd";

OR,

char c[5]="abcd";

OR,

char c[]={'a','b','c','d','\0'};

OR;

char c[5]={'a','b','c','d','\0'};

 Difference between above declarations are, when we declare char as


“c[5]“, 5 bytes of memory space is allocated for holding the string
value.
 When we declare char as “c[]“, memory space will be allocated as
per the requirement during execution of the program.

Write a C program to how to read string from terminal.


#include <stdio.h>
main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
}

30
Example program for displaying string:
#include <stdio.h>
main ()
{
char string[20] = "dbsGroups";
printf("The string is : %s \n", string );
getch();
}

STRING HANDLING FUNCTIONS

The string-handling functions are implemented in libraries.  They are

1. Strcpy()

2. Strcmp()

3. Strcat()

4. Strlen()

5. Strlwr()

6. Strupr()

7. Strchr()

8. Strstr()

9. Strrev()

1. Strcpy()

This library function is used to copy from one string to another string.

Syntax: strcpy (destination, source)

31
Example:

main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
strcpy ( target, source ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
}

2. Strcmp()

This library function is used to compare two strings.

Syntax: strcmp(str1, str2).

Ex :

main()
{
char str1[20] = “cse”;
char str2[20] = “eee”
int ch;
clrscr();
ch=strcmp(str1,str2);
if(ch==0)
printf("\n the strings are equal:");
else
printf("\n the strings are not equal:");
getch();
}

3. Strcat()

This library function concatenates a string onto the end of the other string. 
32
Syntax: strcat(string1,string2)

Ex :

main()
{
char str1[30]="www.cprogramming";
char str2[15]="expert.com";
clrscr();
strcat(str1,str2) :
printf(" %s ”, str1);
getch();

4. Strlen()

This library function returns the length of a string. 

Syntax: strlen(string);

Ex:
#include <stdio.h>
#include <string.h>
main()
{
char name[80] = “ programming” ;
int l;
l= strlen( name );
printf("The lenght is %d", l );
}

5. Strlwr():

33
It converts string to lowercase.

Syntax: strlwr(string)

Ex:
#include <stdio.h>
#include <string.h>
main()
{
char name[80] = “ PROGRAMMING ”
strlwr( name );
printf("The name is lower case is %s", name );
}
6. Strupr()

It converts string to uppercase.

Syntax: strupr(string)

Ex:

#include <stdio.h>
#include <string.h>

main()
{
char name[80] = “ programming”
strupr( name );
printf("The name is uppercase is %s", name );
}
7. Strchr()

The strchr function returns a pointer to the first occurrence of character c


in string or a null pointer if no matching character is found.

34
Syntax: strchr(char string[], int c);
 str -- This is the C string to be scanned.

 c -- This is the character to be searched in str.

Ex:
main()
{
char s[];
char buf [] = "This is a test";

s = strchr (buf, 't');

if (s != NULL)
printf ("found a 't' at %s\n", s);
}

8. Strstr()

The strstr function returns a pointer within string2 that points to a string
identical to string1. If no such sub string exists in source a null pointer is
returned.

Syntax: strstr(char string2[], char string1[]);


Ex:
#include <stdio.h>

main()
{
char s1 [] = "My House is small";
char s2 [] = "My Car is green";
printf ("Returned String 1: %s\n", strstr (s1, "House"));
printf ("Returned String 2: %s\n", strstr (s2, "Car"));
}
9. strrev() function
35
 strrev( ) function reverses a given string in C language. Syntax for
strrev( ) function is given below.

Syntax: strrev(string);

Ex:

main()
{
char name[30] = "Hello";
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
getch();
}

Strings using two dimensional arrays (Array of


strings)

To create a array of strings we use a two dimensional character array.

Syntax: char string[number of strings][length of each string]

To read a strings we use gets().

36

You might also like