0% found this document useful (0 votes)
28 views

PC UNIT-2 Material

Uploaded by

MEGHANA BONTHU
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)
28 views

PC UNIT-2 Material

Uploaded by

MEGHANA BONTHU
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/ 66

UNIT-II: Conditional Branching and Loops:

Syllabus

Writing and evaluation of conditionals and consequent branching,

Iteration and loops,

Arrays (1-D, 2-D),

Character arrays and

Strings.
Decision statements (or) selection statements (or) conditional statements:

C language possesses decision-making capabilities by supporting the following statements:

If statement

Switch statement

These statements are popularly known as decision-making statements. Since these statements
control the flow of execution, they are also known as control statements.

Decision making with if statement

The if statement is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression. It takes the following form:

If (test-expression)

It allows the computer to evaluate the expression first and then, depending on whether the
value of the expression is true or false, it transfers the control to a particular statement.

The if statement may be implemented in different forms depending on the complexity of


conditions to be tested. The different forms are:

 simple – if statement
 if – else statement
 nested – if else statement
 Else – if ladder
 Switch statement

1. Simple – if statement

The general form of a simple if statement is

Syntax :
if (condition)

Statement-block;

Statement-x;

The statement-block may be a single statement or a group of statements. If the condition is


true, the statement-block will be executed; otherwise the statement-block will be skipped and
the execution will jump to the statement-x;

Note: When the condition is true, both the statement-block and the statement-x are executed
in sequence.

Flow chart
Con
True ditio False

Statement (s)

Program /* checking whether a number is greater than */

main ( )

int a;

printf (“enter a number”);


scanf (“%d”, &a);

if (a>50)

printf (‘%d is greater than 50”, a);

Output

1) enter a number 60 2) enter a number 20

60 is greater than 50 no output.

2. if … else statement

The if … else statement is an extension of simple if statement. It takes the following general
form

Syntax:

if (condition)

True block statement(s)

else

False block statement(s)

statement-x
If the condition is true, then the true-block statement(s), immediately following the if
statements are executed.: otherwise, the false-block statements are executed. In either case,
either true-block or false-block will be executed, not both. In both cases, the control is
transferred subsequently to the statement-x.

Flow chart

True Con False


ditio

True block False block


statement(s) statement (s)

Program

/* checking for even (or) odd number */

main ( )

int n;

printf (“enter a number”);


scanf (“%d”, &n);

if (n%2 ==0)

printf (‘%d is even number”, n);

else

printf( “%d is odd number”, n”);

Output

1) enter a number 10 2) enter a number 5

10 is even number 5 is odd number

3. Nested if - else statement

If---else statement inside another if---else statement is called as nested if---else statement.

When a series of decisions are involved, we may have to use more than one if…else
statement in nested form.

Syntax:

if (condition1)

if (condition2)

stmt1;

else

{
stmt2;

else

if (condition3)

stmt3;

else

stmt4;

Flow chart

True Con False


ditio

True Con False True Con False


ditio ditio

Stmt1 Stmt2 Stmt3 Stmt4


Program /* largest of 3 numbers */

main ( )

int a,b,c;

printf (“enter 3 numbers”);

scanf (“%d%d%d”, &a, &b, &c);

if (a>b)

I f (a>c)

printf (‘%d is largest”, a);

else

printf (‘%d is largest”, c);

else

if (b>c)

printf (‘%d is largest”, b);


else

printf (‘%d is largest”, c);

Output

enter 3 numbers = 10 20 30

30 is largest

4. Else – if ladder

This is the most general way of writing a multi-way decision. A multi-way decision is a chain
of ifs in which the statement associated with else is an if. It takes the following general form

Syntax

if (condition1)

stmt1;

else if (condition2)

stmt2;

-----

else if (condition n)

stmnt;

else

stmt x ;
flow chart

True Cond False


ition
1?

True Con False


ditio

Stmt1

------
Stmt2

Cond
True ition False

Stmt n Stmt x

Program /* finding roots of quadratic equation */

#include <math.h>

main ( )

int a,b,c,d;

float r1, r2
printf (“enter a,b,c values”);

scanf (“%d%d%d”, &a, &b, &c);

d= b*b – 4*a*c

if (d>0)

r1 = (-b+sqrt(d)) / (2*a);

r2 = (-b-sqrt(d)) / (2*a);

printf (“root1 = %f, root2 == %f, r1, r2);

else if (d= = 0)

r1 = -b / (2*a);

r2 = -b/ (2*a);

printf (“root1 = %f, root2 == %f, r1, r2);

else

printf (‘roots are imaginary”);

Output

1) enter a,b, c values : 1 4 3

Root 1 = -1

Root 2 = -3

2) enter a,b, c values : 1 2 1


Root 1 = -1

Root 2 = -1

3) enter a,b, c values : 1 2 3

roots are imaginary

Switch statement

C has a built-in multiway decision statement known as switch. It is used to select one among
multiple decisions. The switch statement tests the value of a given variable (or expression)
against a list of case values and when a match is found, a block of statements associated with
that case is executed.

Syntax

switch (expression)

case value1 : stmt1;

break;

case value2 : stmt2;

break;

------

default : stmt – x;

}
Flow chart

Switch
(express
ion)

Exp =value1 Stmt1

Exp =value2
Stmt2

default Stmt-x

The expression is an integer expressions or characters. Value1, value2 are constats or


constant expressions (evaluable to an integral constant) and are known as case labels. Each
of these values should be unique with in a switch statement. There is no need to put braces
around these blocks. Note that case labels end with a colon( : )

When the switch is executed, the value of the expression is successfully compared
against the values value-1,valu-2,---. If a case is found whose values match with value of the
expression, then the block of statements that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and
causes 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 matches fail and the control goes to the statement-x.

Program

main ( )

int n;

printf (“enter a numbers”);

scanf (“%d”, &n);

switch (n)

case 0 : printf (“zero”)

break;

case 1 : printf (‘one”);

break;

default : printf (‘wrong choice”);

Output

enter a number
1

one

It i1s possible to nest the switch statements. That is, a switch may be part of a case statement.
ANSI C permits 15 levels of nesting.

Some key rules for using switch statement:

1. The switch expression must be an integral type.


2. Case labels must be constants or constant expressions.
3. Case labels must be unique. No two labels have the same value.
4. Case labels must end with colon( : ).
5. The break statement transfers the control out of the switch statement.
6. The break statement is optional. That is, two or more case labels may belong to the
same statements.
7. The default label is optional. If present, it will be executed when the expression does
not find a matching case label.
8. Threre can be at most one default label.
9. The default may be placed anywhere but usually placed at the end.
10. It is permitted to nest switch statements

Loop control statements

Looping or iterative statements are used for running a particular set of code for any number
of times. Iterative statements consist two parts—head and body. The head of the statement
decides the number of times the body of the statements are to be executed.

In looping, a sequence of statements are executed until some conditions for the termination of
the loop are satisfied.

A looping process, in general, would include the following four steps:

1. Setting and initialization of a condition variable.


2. Test for a specified value of the condition variable for execution of the loop
3. Execution of the statements in the loop.
4. Incrementing or decrementing the condition variable.
The C language provides three constructs for performing loop operations.

They are

 for loop
 while loop
 do-while loop

for loop

The for loop is an entry-controlled loop that provides loop control structure. The general form
of the for loop is

Syntax

for (initialization ; condition ; increment / decrement)

body of the loop

Flow chart

False
Initialization Increment/

condition decrement
True

Body of the loop


for statement contains 3 parts

initialization is usually an assignment statement that is used to set the loop control variable

The condition is a relational expression that determines when the loop will exit.

The increment/decrement part defines how the loop control variable will change each time
loop is repeated

loop continues to execute as long as the condition is true

Once the condition is false, program continues with the next statement after for loop.

The execution of the for statement is as follows

1) Initialisation of the control variable is done first, using assignemnt statements such as i=1
and count=0. The variables i and count are known as loop-control variabels.

2) The value of the control variable is tested using the test-condition. The test-condition os a
relational expression, such as i<10 that determines when the loop will exit. If the condtiion is
true, the body of the loop is executed; otherwise the loop is terminated and the execution
continues with the statement that immediately follows the loop.

3) When the body of the loop is executed, the control is transfered back to the for statemetn
after evaluating the last staement in the loop. Now the control variable is incremented using
an assignement statement such as i=i+1 and the new value of the control variable is again
tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of
the loop is again executed. This process continues till the value of the control variable fails to
satisfy the test-condition.

Program

main( )
Output
{
1

3
4

int k;

for (k = 1; k<5; k++)

printf (”%d”,k);

Additional features of for loop

 More than on variable can be initialized at a time in the for statement


Ex: for(i=1 , j=0; i<10; i++)

Note that the initialization section has two parts i=1 and j=0 seperated by comma.

 Like the initialization section, the increment section may also have more than one
part. The multiple arguments in the increment section are separated by commas.
Ex: for(i=1 , j=10; i <= j; i++, j--)

 Further, the test-condition may have any compound relation and the testing need not
be limited only to the loop control variable.
Ex:

sum = 0;

for( i = 1 ; i < 20 && sum < 100 ; ++i)

{
sum=sum + i;

 Another unique aspect of for loop is that one or more sections can be omitted, if
necessary.
Ex:

m = 5;

for( ; m != 100 ; )

m = m + 5;

Here both initialization and increment sections are omitted in the for statement. The
initilisation has been done before the for statement and the control variable is incremented
inside the loop. In such cases the sections are left blank. However, the semicolons separating
the sections must remain. If the test-condtion is not present, the for statement sets up an
infinite loop.

Nesting of for loops

Nesting of loops, that is, one for statement within another for statement, is allowed in C. For
example two loops can be nested as shown bellow

-----------------------------------

------------------------------------

for( i = 1 ; i < 10 ; ++i)

----------------------
for( j = 1; j != 5; ++j)

-----------------------

-----------------------

------------------------------

-----------------------------

while loop

The simplest of all the looping structures in C is the while statement.

Syntax

while (condition)

body of the loop

The while is an entry-controlled loop statement. The condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test-
condition is once again evaluated and if it is true, the body is executed once again. This
process of repeated execution of the body continues until the test-condition finally becomes
false and the control is transferred out of the loop. On exit, the program continues with the
statement immediately after the body of the loop.
Flow chart initialization

Is
expressio False

True

Body of the loop

Incr/ dec

Intialization is done before the loop

Loop continues as long as the condition is true

Incriminations and decrementation part is done within the loop

Program

main( )
Output
{
1
int k;
2
k = 1;
3

4
while (k< = 5)

printf (”%d”,k);

k++;

do-while loop

The while loop construct, makes a test of condition before the loop is executed. Therefore,
the body of the loop may not be executed at all if the condition is not satisfied at the very first
attempt. In some situations it might be necessary to execute the body of the loop before the
test is performed. Such situations can be handled with the help of the do- while statement.

Syntax

Initialization

do

body of the loop

inc/ dec

} while (condition);

On reaching the do statement, the program proceeds to evaluate the body of the loop first. At
the end of the loop, the condition in the while statement is evaluated. If the condition is true,
the program continues to evaluate the body of the loop once again. This process continues as
long as the condition is true. When the condition becomes false, the loop will be terminated
and the control goes to the statement that appears immediately after the while statement.
Since the condition is evaluated at the bottom of the loop, the do---while construct provides
an exit-controlled loop and, therefore, the body of the loop is always executed atleast once.

Flow chart
initialization

Body of the loop

True

Is
expressio
Incr/ dec

Flase

Program

main( )
Output
{
1
int k;
2
k = 1;
3
do
4
{

printf (”%d”,k);
k++;

} while (k == 5);

Other statements related to loops

 break
 continue
 goto

1)break (jumping out of a loop)

An early exit from a loop can be accomplished by using the break statement or goto
statement. break statement can be used within while, do-while, for and switch statement. The
use of break in loops is illustrated in following fig:

Summary:

It is a keyword used to terminate the loop (or) exit from the block

The control jumps to next statement after the loop (or) block

‘break is used with for, while, do-while and switch statement

When break is used in nested loops then only the innermost loop is terminated

When a break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop. When the loops are
nested, the break would only exit from the loop containing it. That is, the break will exit only
a single loop.

Program

main( )
Output
{ int i;
1

3
for (i=1; i<=5; i++)

printf (”%d”, i);

if (i= =3)

break;

2) continue (skipping a part of a loop)

Like the break statement, C supports another similar statement called the continue
statement. However, unlike the break statement that causes the loop to be terminated, the
continue, as the name implies, causes the loop to be continued with the next iteration after
skippin any statements in between. The continue statement tells the compiler, “skip the
following statements and continue with the next iteration”.

It is a keyword used for continuing the next iteration of the loop

It skips the statements after the continue statement

It is used with for, while and do-while

Syntax

Stmt1;

Stmt2;

continue;

Stmt3;

Stmt4;
}

Program
Output
main( )
1
{
3
int i;
4
for (i=1; i<=5; i++)
5
{

if (i= =2)

continue,

printf(“%d”, i)

3) goto

C supports the goto statement to branch unconditionally from one point to another in the
program. The goto requires a label in order to identify the place where the branch is to be
made. A label is any valid name, and must be followed by a colon( : ) . The label is placed
immediately before the statement where the control is to be transferred. The general form of
goto is shown in fig

Forward jump backward jump


Syntax

goto label; label :stmt

---- ----

---- ----
---- ----

label : stmt goto label;

The label : can be anywhere in the program either before or after the goto label; statement.
During running of a program when a statement like goto begin; is met, the flow of control
jumps to the statement immediately following the label begin. This happens unconditionally.

Note that a goto breaks the normal sequential execution of the program. If the label: is
before the statement goto label; a loop will be formed and some statements will be executed
repeatedly. Such a jump is known as a backward jump. On the other hand, if the label: is
placed after the goto label; some statements will be skipped and the jump is known as a
forward jump.

Program
Output
main( )
Hello
{
you
printf(’Hello”);

goto l1;

printf(”How are”);

l1: printf(”you”);

}
Introduction to Arrays

ARRAYS

 Array: An array is a sequenced collection of related data items that share a comman
name
A particular value in an array is identified using its “index number” or “subscript”

Advantage

The ability to use a single name to represent a collection of items and to refer to an item by
specifying the item number enables the user to develop concise and efficient programs

Declaration and definition of array

An array must be declared and defined before it can be used. Array declaration and definition
tell the compiler the name of the array, the type of each element, and the size or number of
elements in the array.

Syntax : for declaring array:

datatype array_name [size];

Eg:

1. float height [50]

This declares ‘height’ to be an array containing 50 float elements

2. int group[10]

 This declares the ‘group’ as an array to contain a maximum of 10 integer constants


 Individual elements are identified using “ array subscripts”
 While complete set of values are referred to as an array, individual values are called
“elements”

Eg: To represent a set of 5 numbers by an array, it can be declared as follows

int a[5];

 Then computer reserves 5 storage locations each of 2 bytes.


a[0]

a[1]

a[2]

a[3]

a[4]

 First element is identified by subscript ‘zero’ i.e., a[0] represents first element of the
array.
 If there are ‘n’ elements in array then subscripts range from 0 to n-1

Array Initialization

To store values into an array it can be done as follows.

a[0] = 10; 10 a[0]

a[1] = 20; 20 a[1]

a[2] = 30; 30 a[2]

a[3] = 40; 40 a[3]


a[4] = 50; 50 a[4]

An array can also be initialized at the time of declaration as follows

int a[5] = { 10,20,30,40,50};

Here 5 elements are stored in array ‘a’. The array elements are stored sequentially in separate
locations.

Reading of array elements begins from ‘0’. Array elements are called by array names
followed by the element numbers.

Ex: a[0]

Calling array elements:-

A[0] refers to the 1st element i.e 10

A[1] refers to the 2nd element i.e 20

A[2] refers to the 3rd element i.e 30

A[3] refers to the 4th t element i.e 40

A[4] refers to the 5th element i.e 50

Any reference to the arrays outside the declared limits would not necessarily cause an error.
Rather it might result in unpredictable program results.

Character array

The C language treats character strings simply as arrays of characters. The size in a character
string represents the maximum number of characters that the string can hold.

For ex: char name[10];

declares the name as a character array(sring) varalbe that can hold a maximum of 10
characters. Suppose we read the following string constant into the string variable name.
“WELL DONE”

Each character of the string is treated as an element of the array name and is stored in the
memory as follows

‘W’

‘E’

‘L’

‘D’

‘O’

‘N’

‘E’

‘\0’

When the compiler sees a character string, it terminates it with an additional null character(‘\
0’). Thus, the element name[10] holds the null character ‘\0’. When declaring character
arrays, we must allow one extra element space for the null terminator.

Types of arrays

We can use arrays to represent not only simple lists of values but also tables of data in two,
three or more dimensions.

Arrays are broadly classified into 3 types. They are

1) one – dimensional arrays


2) two – dimensional arrays
3) Multi – dimensional arrays
1. one – dimensional arrays
A list of items can be given one variable name using only one subscript and such a variable is
called a one-dimensional array.
Declaration of one-dimensional arrays

Like any other variable , arrays must be declares before they are used so that the compiler can
allocate space for them in memory.

Syntax: datatype array-name [size];

The datatype specifies the type of element that will be contained in the array, such as int,
float, or char and the size indicates the maximum number of elements that can be stored
inside the array.

for ex: int group[10];

declares the group as an array to contain a maximum of 10 integer constatnts.

Initialization of one-dimensional arrays

After an array is declared, its elements must be initialized. Otherwise, they will contain
“garbage”.

An array can be initialized in 2 ways.

a) compile time initialization


b) Runtime initialization

a) compile time initialization


We can initialize the elements of arrays in the same way as the ordinary variable when
they are declared. The general form of initialization of array is:

type array-name[size] = { list of values };

The values in the list are separated by commas. For example, the statement

int number[3] = { 0 , 0 , 0 };

will declare the variable number as an array of size 3 and will assign zero to each
element.
 If the number of values in the list is less than the number of elements, then only that
many elements will be initialized. The remaining elements will be set to zero
automatically.
For ex: int total[5]= {10,20,30} will initialize the first three elements to 10, 20
and 30 and the remaining two elements to zero.

 If the number of values in the list is greater than the number of elements, then it will
show a syntax error that too many initializations for this array.
The size may be omitted. In such cases, the compiler allocates enough space for all
initialized elements. For example the statement

int counter[ ] = { 1, 1, 3, 1};

will declare the counter array to contain four elements with initil values 1,1,3 and 1 .

Character arrays may be initialized in a similar manner. Thus the statement

char name[ ] = { ‘J’ ,’O’, ‘H’, ‘N’ , ‘\0’ };

declares the name to be an array of five characters, initialized with the string “JOHN”
ending with the null character. Alternatively , we can assign the string literal directly as
under:

char name[ ] = “JOHN”;

If we have more initializers than the declared size, the compiler will produce an error. That
is the statement

int number[3] = { 10, 20 , 30 , 40 };

wil not work. It is illegal in C.

The total size in bytes for a single dimensional array is computed as shown below.

Total bytes = sizeof( data-type ) * size of array;


Program for compile time initialization and sequential access using for loop

main ( ) storing

int a[5] = {10,20,30,40,50}; a[0] 10

int i; a[1] 20

clrscr ( ); a[2] 30

printf (“elements of the array are”); a[3] 40

for ( i=0; i<5; i++) a[4] 50

printf (“%d, a[i]);

getch ( );

}
accessing

Output: Elements of the array are

10 20 30 40 50

b) Run time initialization


An array can be explicitly initialized at run time.

Program for runtime initialization and sequential access using for loop

main ( )

{
int a[5],i;

clrscr ( );

printf (“enter 5 elements”);

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


Storing / assigning values to element of an
scanf(”%d”, &a[i]); array

printf(“elements of the array are”);


Accessing the elements of the aray
for (i=0; i<5; i++)

printf(”%d ”, a[i]);

getch ( );

output

enter 5 elements 10 20 30 40 50

elements of the array are : 10 20 30 40 50

Note :

The output of compile time initialized program will not change during different runs of the
program

The output of run time initialized program will change for different runs because user is
given a chance of accepting different values during execution.

2. Two – dimensional arrays

 These are used in situations where a table of values have to be stored (or) in matrices
applications
 Declaration Syntax :
datatype array_ name [rowsize] [column size];
 Eg: int a[5] [5];
 No of elements in array = rowsize *columnsize = 5*5 = 25
Initialization :

Like the one–dimensional arrays, two-dimensional arrays may be initialized by following


their declaration with a list of values enclosed in braces. For example,

int table[2][3] = { 0, 0, 0, 1, 1, 1 };

initializes the elements of the first row to zero and the second row to one. The initialization is
done row by row. The above statement can be equivalently written as

int table[2][3] = { { 0, 0, 0 }, {1, 1, 1} };

commas are required after each brace that closes off a row, except in the case of the last row.

When the array is completely initialized with all values, explicitly, we need not specify the
size of the first dimension. That is the statement

int table[ ] [3] = {

{ 0, 0, 0 },

{ 1, 1, 1 }

};

is permitted.

If the values are missing in an initilizer, they are automatically set to zero. For example, the
statement

int table[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.

When all the elements are to be initialized to zero, the following short-cut method may be
used.

int m[3][5] = { { 0 }, { 0 }, { 0 } };
The first element of each row is explicitly initialized to zero while other elements are
automatically initialized to zero. The following statement will also achieve the same result.

int m[3][5] = { 0, 0};

Program for compile time initialization and sequential access using nested for loop

main ( )

int a[3][3] = a[0] [0] a[0] [1] a[0] [2]


{10,20,30,40,50,60,70,80,90};
10 20 30
int i,j;
a[1 [0] a[1] [1] a[1] [2]
clrscr ( );
40 50 60
printf (“elements of the array are”);
a[2] [0] a[2] [1] a[2] [2]
for ( i=0; i<3; i++)
70 80 90
{

for (j=0;j<3; j++)

printf(“%d \t”, a[i] [j]);

printf(“\n”);

getch ( );
}

output

elements of the array are:

10 20 30

40 50 60

70 80 90

Program for runtime initialization and sequential access using nested for loop

main ( )

int a[3][3] ,i,j;

clrscr ( );

printf (“enter elements of array”);

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

for (j=0;j<3; j++)

scanf(“%d ”, &a[i] [j]); a[0] [0] a[0] [1] a[0] [2]

} 10 20 30

} a[1 [0] a[1] [1] a[1] [2]

printf(“elements of the array are”); 40 50 60

for ( i=0; i<3; i++) a[2] [0] a[2] [1] a[2] [2]

{ 70 80 90

for (j=0;j<3; j++)


{

printf(“%d\t ”, a[i] [j]);

printf(“\n”)

getch( );

output

Enter elements of array : 1 2 3 4 5 6 7 8 9

Elements of the array are

1 2 3

4 5 6

7 8 9

3. Multi –dimensional arrays

 ‘C’ allows arrays of 3 (or) more dimensions


 The exact limit is determined by compiler
Syntax:

 datatype arrayname [size1] [size2] ----- [sizen];


 eg: for 3 – dimensional array:
int a[3] [3] [3]

 No of elements = 3*3*3 = 27 elements


Prorgam

main ( )

{
int a[2][2] [2] = {1,2,3,4,5,6,7,8};

int i,j,k;

clrscr ( );

printf (“elements of the array are”);

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

for (j=0;j<2; j++)

for (k=0;k<2; k++)

printf(“%d ”, a[i] [j] [k]);

getch( );

}Output : Elements of the array are :1 2 3 4 5 6 7 8

STRINGS

Introduction to strings

A string is a series of characters treated as a unit. C does not support strings as a data type.
However, it allows us to represent strings as character arrays. In C, therefore a string variable
is any valid C variable name and is always declared as an array of characters.

C strings :

A C string is a variable-length array of characters that is delimited by the null character


Storing strings

In C, a string is stored in an array of characters. It is terminated by the null character (‘\0’).


Because a string is stored in an array, the name of the string is a pointer to the beginning of
the string.

H E L L O \0

Fig: Storing strings

The following fig shows the difference between a character stored in memory and a one-
character string stored in memory. The character requires only one memory location. The one
character string requires two memory locations: one for the data and one for the delimeter.

String literals

A string literal or as it also known, string constant is a sequence of characters enclosed in


double quotes.

Ex: “Hello”

“ C is a high level language”

When string literals are used in a program, C automatically creates an array of characters,
initializes it to a null delimited string, an stores it, remembering its address.

Declaring strings :

Since strings are a sequence of characters, it is only natural way that the structure used to
store string variables is the character array.

Syntax:

char stringname [size];

In defining the array to store a string we must provide enough space for the data and the
delimiter. The storage structure, therefore must be one byte larger than the maximum data
size. A string declaration for an eight character string, including its delimeter, is shown below

char str [ 9 ] ;

The name of the string is a pointer constant.


Initializing strings

Like numeric arrays, character arrays may be initialized when they are declared.

C permits a character array to be initialized in either of the following forms:

char city [ 9 ] = “New York” ;

char city [ 9 ] = { ‘N’ , ‘e’ , ‘w’ , ‘ ‘ , ‘Y’, ‘o’ , ‘r’ , ‘k’ ,’\0’ };

The reason that city had to be 9 elements long is that the string New York contains 8
characters and one element space is provided for the null terminator.

Note that when we iniitlaize character array by listing its elements, we must supply explicitly
the null character.

C also allows us to initialize a character array with out specifying the number of elements. In
such cases, the size of the array will be determined automatically, based on the number of
elements initialized. For example the statement

char str [ ] = { ‘g’ , ‘o’ , ‘o’ , ‘d’ , ‘\o’ };

defines the array string as a five element array.

We can also declare the size much longer than the string size in the initialize. That is the
statement

char str[ 10 ] = “Good” ;

is permitted. In this case, the computer creates a character array of size 10, places the value
“Good” in it, terminates with the null character, and initializes all other elements to null. The
storage will look like:

However, the following declaration is illegal.

char str[ 2 ] = “ Good”;

This will result in a compile time error.

Also note that we can’t separate the initialization form declaration. That is,

char strr3[ 5 ];
str[ 5 ] = “Good” ; is not allowed.

Similarly,

char s1[ 4 ] = “abc”;

char s2[4 ];

s2 = s1; //Error

is not allowed.

An array can’t be used as the left operand of an assignment operator.

Char *ptr=”good day”;  This creates a string for the literal and then stores its address
in the string pointer variable, ptr

Accessing

 There is a control string “%s” used for accessing the string till it encounters ‘\0’
Program

main ( )

char a[10] = “Hello”;

clrscr ( );

printf ( “ given string is %s”,a)

getch ( );

Output : Given string is Hello


String Input/Output functions

Statement (s)

Condition? Condition?

C provides two basic ways to read and write strings.

First, we can read and write strings with the formatted input/output functions, scanf/fscanf
and printf/fprintf.

Second, we can use a special set of string only functions, get string(gets/fgets) and put string
(puts/fputs).

Formatted string input/output:

Formatted string input : scanf / fscanf

The familiar input/output function scanf can be used with %s format specification to read in a
string of characters.
Ex: char address[10];

Scanf(“%s” , address);

An address operator( & ) is not required, since it is already a pointer constant. Infact, it would
be an erroe to use one.

The scanf function automatically terminates the string that is read with a null character and
therefore the character array should be large enough to hold the input string plus the null
character. We can also specify the field width using the form %ws in the scanf statement for
reading a specified number of characters from the i/p string.

Ex: scanf(“%ws”, name);

Here, two things may happen.

(1) The width w is equal to or greater than the number of characters typed in. The entire
string will be stored in the string variable.
(2) The width w is less than the number of characters in the sring. The excess characters
will be truncated and left unread.
Consider the following statements:

char name[ 10 ];

scanf( “%5s” , name);

The i/p string HAI will be stored as

The i/p string KRISHNA will be stored as

Formatted string output: printf / fprintf

The printf function with %s format prints strings to the screen. The format %s can be used to
display an array of characters that is termiantaed by a null character.

For example the statement printf(“%s”, name);


Can be used to display the entire contents of the array name. We can also specify the
precision with which the array displayed. For instance the specification %10.4 indicates that
the first four characters are to be printed in a field width of 10 columns.

However, if we include the minus sign in the specification (Ex: % - 10.45), the string will be
printed left justified.

Ex:

Void main()

Char country[ 15 ] = “United kingdom”; Output:

Printf(“%15s\n”, country); United kingdom

Printf(“%5s\n”, country); United Kingdom

Printf(“%15.6s\n”, country); Uunited

Printf(“%-15.6s\n”, country); United

Printf(“%15.0s\n”, country);

Printf(“%.3s\n”, country); Uni

Printf(“%s\n”, country); United kingdom

The o/p illustrates the following features of the %s specifications

(1) When the field width is less than the length of the string, the entire string is printed.
(2) The integer value on the right hand side of the decimal point specifies the number of
characters to be printed.
(3) When the number of characters to be printed is specified as zero, nothing is printed.
(4) The minus sign in the specification causes the string to be printed left-justified.
(5) The specification %ns prints the first n characters of the string.

gets( )
Another and more convenient method of reading a string of text containing white spaces is to
use the library function gets available in the <stdio.h> header file. This is a simple function
with one string parameter and called as under

gets( str );

str is a string variable declared properly. It reads characters into str from the keyboard until a
new-line character is encountered and then appends a null character to the string. Unlike
scanf, it does not skip white spaces.

For example, the code segment

char line[ 80 ];

gets(line);

printf(“%s” , line);

reads a line of text from the keyboard and displays it on the screen.

C does not provide operators that work on strings directly. For instance, we cannot assign one
string to another directly.

For example the assignment statements

String = “ABC”;

String1= string2 are not valid.

Puts( )

Another and more convenient way of printing string values is to use the function puts
declared in the header file <stdio.h>. This is a one parameter function and invoked as under

Puts ( str );

Where sr is a string variable containing a string value. This prints the value of the string
variable str and then moves the cursor to the beginning of the next line on the screen.

For example the program segment

Char line[ 80 ];
gets( line );

puts( line );

reads a line of text from the keyboard and displays it on the screen.

program : using printf ( ) and scanf ( ) for reading & writing strings.

main ( )

char a[30];

printf(“enter your name”);

scanf ( “%s”,a);

printf (“your name is %s”,a);

getch ( );

Output

1. Enter your name : Ramu 2. Enter your name : Ram kumar

Your name is Ramu Your name is Ram

Note :

1. ‘&’ is not used for accepting string because name of the string itself specifies the base
address of the string
2. space is not accepted as a character by scanf( )
3. ‘\0’ is automatically placed by the compiler at the end.

Program : Using gets ( ) and puts ( ) for reading and writing strings.

main ( )

{
char a[30];

printf ( “enter your name”);

gets (a);

printf(“Your name is”);

puts (a);

Out put

1. Enter your Name : Ramu 2) Enter your name : Ram kumar


Your name is ramu Your name is Ram kumar

Note : Space is also accepted as a character by gets ( )

Sting handling (or) String manipulation functions

Strings Library functions

 There are some predefined functions designed for handling strings which are available
in the library “string.h”
They are :

1) strlen ( ) 6. strcmp ( )
2) strcpy ( ) 7. strncmp ( )
3) strncpy ( ) 8. strrev ( )
4) strcat ( )
5) strncat ( )
1). strlen ( )

 This function gives the length of the string i.e. the number of characters in a
string.
Syntax:

int strlen (string name)


program

#include <string.h>

main ( )

char a[30] = “Hello”;

int l;

l = strlen (a);

printf (length of the string = %d”, l);

Output

Length of the string = 5

Note : “\0” will not be counted as a character.

2). strcpy ( )

 This function is used for copying source string into destination string
 The length of the destination string must be greater than (or) equal to that of the
source string
Syntax: strcpy (Destination string, Source String);

Eg:

1) char a[50]; 2) char a[50];

Strcpy (“Hello”,a); strcpy ( a,”hello”);

o/p: error o/p: a= “Hello”


program

#include <string.h>

main ( ) a

{
H E l l o to
char a[50], b[50];

clrscr ( )
H E l l o to
b

printf (“enter a source string”);

scanf(“%s”, a);

strcpy ( b,a);

printf (“copied string = %s”,b);

Output

Enter a source string : Hello

Copied string = Hello

3) strncpy ( )

 This function is used for copying ‘n’ characters of source string into destination
string
 The length of the destination string must be greater than (or) equal to that of the
source string
Syntax:
strncpy (Destination string, Source String, n);

program

#include <string.h>

main ( ) a

{
H E l l o \o
char a[50], b[50];

clrscr ( ) b
H E l \o
printf (“enter a string”);

gets (a);

strncpy (b,a,3);

b[3] = ‘\0’;

printf (“copied string = %s”,b);

Output

Enter a string : Hello

Copied string = Hel

s1

J a n 1 0 2 0 1 0 \0

It is also used for extracting substrings;

Eg: char result[10], s1[15] = “Jan 10 2010”;

strncpy (result, &s1[4], (2);

1 0 \o
result[2] = ‘\0’ result

o/p :Result = 10

4) strcat ( ):

 This is used for combining or concatenating two strings.


 The length of the destination string must be greater than the source string
 The resultant concatenated string will be in the source string.
Syntax:

strcat (Source String, Destination string);

program

#include <string.h>

main()

char a[50] = “Hello”;

char b[20] = “Good Morning”;

clrscr ( );

strcat (a,b);

printf(“concatenated string = %s”, a);

getch ( );

Output

Concatenated string = Hello Good Morning

5) strncat ( ):

 This is used for combining or concatenating n characters of one string into another.
 The length of the destination string must be greater than the source string
 The resultant concatenated string will be in the source string.

Syntax:

strncat (Source String, Destination string,n);

program

#include <string.h>

main ( )

char a [30] = “Hello”;

char b [20] = “Good Morning”;

clrscr ( );

strncat (a,b,4);

a [9] = ‘\0’;

printf(“concatenated string = %s”, a);

getch ( );

Output

Concatenated string = Hello Good.

String comparison

6) strcmp
 This function compares 2 strings
 It returns the ASCII difference of the first two non – matching characters in both the
strings.

Syntax

int strcmp (string1, string2);

If the difference is equal to zero string1 = string2

If the difference is positive string1> string2

If the difference is negative string1 <string2

eg:

1) char a[10]= “there”


char b[10] = “their” t h e r e \0

strcmp (a,b);

t h e i r \0

Output: string1 >string2


‘r’ > ‘i’

2) char a[10]= “their”


char b[10] = “there” t h e i r \0

strcmp (a,b);

t h e r e \0

Output: string1 <string2


‘i’< ‘r’

3) char a[10]= “there”


t h e r e \0
char b[10] = “there”

strcmp (a,b);

t h e i r \0

Output: string1 =string2

4) char a[10]= “there”


char b[10] = “the” t h e r e \0

strcmp (a,b)

t h e \0

Output: string1 >string2


‘r’ > ‘\0’

5) char a[10]= “the”


char b[10] = “there” t h e \0

strcmp (a,b);

t h e r e \0

Output: string1 <string2

‘\0’ < ‘r’

Program

main ( )

char a[50] b [50];

int d;

clrscr( );
printf (“enter 2 strings”);

scanf (“%s %s”, a,b);

d = strcmp (a,b);

if (d==o)

printf(“%s is equal to %s”, a,b);

else if (d>0)

prinft(“%s is greater than %s”,a,b);

else if (d<0)

printf(“%s is less than %s”, a,b);

getch ( );

7. strncmp ( )

 This function is used for comparing first ‘n’ characters of 2 strings


Syntax :

strncmp ( string1, string2, n)

Eg: char a[10] = “the”;

char b[10] = “there”

strncmp (a,b,3);

Output : Both strings are equal

8. strrev( )

 The function is used for reversing a string


 The reversed string will be stored in the same string
Syntax : strrev (string)
Program

main ( )

char a[50] ;

clrscr( );

printf (“enter a string”);

gets (a);

strrev (a);

printf(“reversed string = %s”,a)

getch ( );

Output : enter a string Hello

Reverstring = olleH

Arrays of strings

Arrays of strings is used to represent a list of srings or list of character arrays i.e list of names
of students in a class, list of names of employees in an organization e.t.c

These names can be treated as a list of strings and they can be implemented as a 2-D array.
Each row in that array represents a name and column represents number of characters in the
array i.e the length of each row.

Ex: char name[10 ] [20];

Here name represents a list of 10 names, each name having the size of 20.

Initializatin of these names array is as follows

Char name[ 3 ] [ 10 ] = ( “naga” , “sai” , “Rama” };


To access the name in the list, we write

Name [ 0 ], name [ 1 ], name [ 2 ]

Ex:

#include<stdio.h>

Void main()

Char name [5][10];

Int I;

Printf(“Enter the strings”);

Scanf(“%s”, &name[i]);

For(i=0; i<5; i++)

Printf(“The entered strings are :%s”, s[i]);

Arrays of pointers: (to strings)

 It is an array whose elements are pointers to the base address of the string
 It is declared and initialized as follows
char *a[ ] = {“one”, “two”, “three”};

Here, a[0] is a pointer to the base address of the string “one”

a[1] is a pointer to the base address of the string “two”

a[2] is a pointer to the base address of the string “three”

o n e \0 t w o \0 t h r e e \0

1234 1238 1242


a [0] 1234

a [1] 1238

a [2] 1242

Array of pointers

Advantage :

 Unlinke the two dimensional array of characters. In (array of strings), in array of


pointers to strings there is no fixed memory size for storage.
 The strings occupy only as many bytes as required hence, there is no was tage of
space.
Program

main ( )

char *a[5] = {“one”, “two”, “three”, “four”, “five”};

int i;

clrscr ( );

printf ( “the strings are”)

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

printf (“%s”, a[i]);

getch ( );

Output

The strings are : one two three four five


Character operations

Character : it can be a character (A-Z(or) a- z);

digit (0-9), a white space, special symbol

Declaration

char a= ‘A’; using a character constant.

Character input / ouput functions

input functions

scanf ( )
ouput functions
getchar ( )
printf ( )
getch ( )
putchar ( )
getche ( )
putch ( )
eg: char a;

scanf(“%c”, &a); printf (“%c”, &a);

a = getchar ( ); putchar (a);

a = getch ( ); putch (a);

Character analysis and conversion functions

 There are some predefined functions available in “ctype.h” library for analyzing the
character input and converting them.

Analysis functions

Function Checks whether entered character is


1. isalpha ( ) An alphabet (or) not

2. isdigit ( ) A digit (or) not

3. isspace ( ) A space, a newline (or) tab

4. ispunct ( ) A special symbol (or) not

5. islower ( ) A lower case letter of alphabet

6. isupper ( ) An upper case letter of alphabet

Converting functions

Function

tolower ( ) Converts an upper case alphabet to lower case

toupper ( ) Converts a lower case alphabet to upper case

Program

#include <ctype.h>

main ( )

char a = ‘D’;

clrscr ( );

if ( isalpha (a))

printf ( “%c is an alphabet”,a);

else

printf (“%c is not an alphabet”,a);

getch ( );
}

Output

D is an alphabet

String/ Number conversion

String to number and number to string conversion

There are 2 functions available for conversion. They are:

1) sscanf( ) - used for converting string to number

2) sprintf ( ) - used for converting number string

1) string to number converstion

 sscanf ( ) – takes a string as an input and converts it into numbers


Syntax:

sscanf (string name, “ control string”, variable list)

for eg: a 02 01 2010 - i/p

%s

02 01 2010

day month year

- o/p

%d %d %d
Program

main ( )

char a[20] = “02 01 2010”;

int day, mon, yr;

clrscr( );

sscanf (a, “%d%d %d”, &day, &mon, &yr);

printf ( “Day =%d”, day);

printf ( “Month = %d”, mon);

printf ( “Year = %d”, yr);

getch ( );

Output

Day = 02

Month = 01

Year = 2010

2. Number to string conversion

 sprintf( ) takes different numeric values as input and converts it into a single string
Syntax :

sprintf ( string name, “control string”, variable list)

for eg: 01 2010 - - i/p


02
%d %d %d

- o/p
02/01/2010

%s

Program

main ( )

char a[50];

int day = 02, mon = 01, yr = 2010;

crlscr( );

sprintf (a, “%d/%d/%d”, day, mon, yr);

prinft ( “today’s date =%s”, s);

getch ( );

Output

Today’s date is 02/01/2010.

String/Data conversion

It may be required for us to convert strings to equivalent data values( of int or float type) and
vice versa. This can be achieved using certain built-in functions of C, as described in table:

Function Description Syntax


atoi ( ) Converts a string to an int atoi(const char* s);
equivalent integer value.

Converts a string to an
atol ( ) equivalent long integer value long atoi(const char* s);

Converts a string to an
atof( ) equivalent long integer value float atoi(const char* s);

Converts floating point char *ecvt(double value,


numbers to equivalent null-
ecvt( ) terminated strings int ndig, int *dec, int *sign)

char *fcvt(double value,

Ecvt and fcvt differ in their int ndig, int *dec, int *sign)
representation of the
argument ndig. In case of
ecvt, it specifies the total
number of characters in the
equivalent string; however in
case of fcvt it specifies the
equivalent number of
characters after the decimal
point.

You might also like