You are on page 1of 37

Programming using C UNIT-III I B.C.

Loop structures/Iterative statements

A portion of program that is executed repeatedly is called a loop.


The ‘C’ programming language contains three different program statements
for program looping.

1. while loop
2. do-while loop.
3. for loop.

The 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 the while loop is
while (test condition)
{
loop statements
}
The while is an entry-controlled loop statement. The test-condition is
evaluated and if the condition is true, then the body of the loop is executed. After
execution of the loop statements, the test-condition is once again evaluated and if it
is true, the loop is executed once again. This process 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 statement of the
loop.

The statement of the loop may have one or more statements. The statements
in the while loop is executed zero or more times depending on the test condition. If
the test condition evaluates to false at the first time, then the statements are never
executed.

Ex:
int i=1;
while(i<=10)
{
printf(“\n C Language”);
i++;
}

In the above example the variable ‘i’ starts with the value 1. The statements in
the while loop will be executed 10 times.

Department of Computer Science 1 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Ex: *Program to print even numbers upto a range.


# include “stdio.h”
# include “conio.h”
main( )
{
int r,i;
clrscr( );
printf(“enter the range:”);
scanf(“%d”,&r);
i=1;
while(i<=r)
{
if (i%2==0)
printf(“%d\t”,i);
i++;
}
getch( );
}

OUTPUT

Enter the range:50

2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
42 44 46 48 50

The do-while loop:

The do-while is a exit – controlled loop. The while loop makes a test of
condition before the loop is executed. Therefore, the statements of the loop may not
be executed at all if the condition is not satisfied at the very first attempt. On some
occasions 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.

The general form of the do-while statement is

do
{
loop statements
}while (test-condition);

Department of Computer Science 2 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

On reaching the do statement, the program procedes to evaluate the


statements of the loop first. At the end of the loop, the test-condition in the while
statement is evaluated. If the condition is true, the program continues to evaluate the
statements 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 test-condition is evaluated at the bottom of the loop, the do-while
construct provides an exit-controlled loop and therefore the statements of the loop is
always executed at least once.

Ex:
i=1;
do
{
printf(“\n C Language”);
i++;
}while(i<=10);

The above do-while loop statements will be executed 10 times.

Ex: * Program if print odd no’s up to a range.

# include “stdio.h”
# include “conio.h”
main()
{
int i=1, range;
clrscr();
printf(“\n Enter range”);
scanf(“%d”,&range);
do
{
if(i%2!=0)
printf(“\t %d”, i);
i++;
}while(i<=range);
getch( );
}

Department of Computer Science 3 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

The for statement:

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

for (initialization; test-condition; updation)


{
loop statements
}

The execution of the for statement is as follows:


1. Initialization of the control variable is done first, using assignment statements.
2. The value of the control variable is tested using the test-condition. The test-
condition is a relational expression, that determines when the loop will exit: If
the condition is true, the statements 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 statements of the loop is executed, the control is transferred back to
the for statement after evaluating the last statement in the loop. Now the
control variable is updated using an assignment statement and the new value
of the control variable is again tested to see whether it satisfies the loop
condition. This process continues till the value of the control variable fails to
satisfy the test-condition.

Ex: for(x=0; x<=9; x++)


{
printf(“%d”,x);
}

In the above example x value will be initialized to 0. Then condition x<=9 is


evaluated, after this the statement in the loop will executed and then updations
statement x++ will be executed. This process continues until condition fails.
One of the important points about the for loop is that all the three actions,
namely initialization, testing, and incrementing are placed in the for statement itself,
thus making them visible to the programmers and users.

Additional features of for loop or variants of for loop:

The for loop in ‘C’ has several capabilities that are not found in other loop
constructs.

i) More than one variable can be initialized at a time in the for statement.

Department of Computer Science 4 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Ex: for(p=1,n=0;n<17;n++)

Like the initialization section, the updation section may also have more than
one part.

Ex: for(n=1,m=50; n<=m;n=n+1,m=m-1)


{
statements;
}

The multiple arguments in the initialization section and increment section are
separated by commas.

i) Test-condition may have any compound relation and the testing need not
be limited to the loop control variable.

Ex: sum=0;

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


{
sum=sum+i;
printf(“%d\n%d”,i,sum);
}

iii) It is also permissible to use expressions in the assignment statements of


initialization and increment sections.

Ex: for(x=(m+n)/2;x>0;x=x/2)

iv) Another unique aspect of for loop is that one or more sections can be
omitted, if necessary.

Ex: m=5;

for(;m!=100;)
{
printf(“%d”,m);
m=m+5;
}

v) If the test-condition is not present, the for statement sets up an infinite


loop. Such loops can be broken using break or goto statements in the loop.

Department of Computer Science 5 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

vi) We can set up time delay loops using the null statement as follows
for(j=1000; j>0; j=j-1);

This loop is executed 1000 times without producing any output; it simply
causes a time delay. The body of the loop contains only a semicolon, known as a
null statement.

Nesting of loops:

A loop can be written in another loop, which is called nesting of loops.

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


for(j=1; j<=10; j++)
printf(“it message”);

In the above example the printf() statement will be executed 100 times.

Ex: Program to display number pyramid using nesting of loops.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,r,t;
clrscr();
printf("Enter no.of rows:");
scanf("%d",&r);
t=0;
for(i=1;i<=r;i++)
{
for(j=1;j<=i;j++)
{
if(t%2==0)
printf("0");
else
printf("1");
t++;
}
printf("\n");
}
getch();
}

Department of Computer Science 6 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

OUTPUT

Enter no.of rows:5


0
10
101
0101
01010
Ex: Program to display star pyramid using nesting of loops.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,rows;
clrscr();
printf("Enter no.of rows:");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
getch();
}

OUTPUT

Enter no.of rows:7


*
**
***
****
*****
******
*******

Goto Statements or Jump Statement: goto is jumping statement in C language,


which transfer the program’s control from a statement is highly discouraged. It
makes difficult to trace the control flow of a program that uses a goto

Department of Computer Science 7 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Syntax:
goto label_name;
..
..
label_name: C-statements

EX:
#include<stdio.h>
#include<conio.h>

void main()
{
int sum=0;
for(int i = 0; i<=10; i++)
{
sum = sum+i;
if(i==5)
{
goto addition;
}
}

addition: printf("%d", sum);


getch();
}

ARRAYS

An array is a set of similar data items that share a common name. The
individual values in an array are called elements. The elements of an array can be of
any data type. All the elements in an array must be of the same type. Array
elements are variables. A particular value is indicated by writing a number called
index number (or) subscript in brackets after the array name. There are two types of
arrays :

1. One-dimensional arrays.
2. Multi-dimensional arrays.

One-dimensional arrays
If a list of items are given one variable name using only one subscript, then it is
called a one-dimensional array.

Department of Computer Science 8 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Declaration of one-dimensional array :

The general form of defining a one-dimensional array is

data type array_name [size];

Where data type should be a valid data type. array_name is the name of the
array and size is the number of elements of the array.

Ex: int a[10], marks[20];


float rates[50];
char name[30];

Ex: int a[20];

The above statement declares a one-dimensional integer array which holds 20


integer elements.

Accessing Elements of the Array


The individual elements of an array can be accessed by its subscript (or) index. The
index of the first element is 0, second element is 1 and so on.

Ex: int a[20];

a[0]  1st element


a[1]  2nd element



a[19]  20th element

In the above declaration ‘a’ is the name of the array, 20 is size of the array.

a[0] a[1] a[2] ……………………………………………………………………………a[19]

In ‘C’ subscript starts from 0. If we declare an array of size n, then we can


refer the elements from ‘0’ to (n-1)th element.

Ex: char name[10];

It declares the ‘name’ as a character array that can hold a maximum of 10


characters.

Department of Computer Science 9 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Initialising of Arrays : The elements of the array may be initialised when they are
declared. The general form of initialisation of array is :
type array_name[size] = { list of values };

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

This will declare the variable ‘number’ as an array of size 3 and will assign
zero to each element.

Ex: float rate[5] = {0.0,15.75,-10};

Will initialise the first three elements to 0.0, 15.75, –10.0 and the remaining
two elements to garbage values.

Ex: int counter[ ] = {1,1,1,1};

The size may be omitted, in such cases, the compiler allocates enough space
for all initialised values. The above example declares the counter array to contain
Four elements with initial values 1.

Storting values in array


Generally values to array elements are assigned using a loop.

Ex: main()
{
int a[10];
int i;
for(i=0;i<10;i++)
scanf(“%d”,&a[i]);
}

The ‘for’ loop in the above example assigns values from keyboard to array elements.
Values can also be assigned to individual elements of an array, just like any other
elements.

Ex: a[5] = 25;


scanf(“%d”,&a[5]);

Department of Computer Science 10 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Ex: main ()
{
float b[10];
int i;
clrscr();
for(i=0; i<10; i++)
scanf(“%f”, &b[i]);
printf(“Array elements are:\n”);
for(i=0; i<10; i++)
printf(“%f\t”,b[i]);
getch();
}

In the above example first for loop assigns the values to elements of array b
from keyboard second for loop displays the elements of array b on console.

Calculating the length of the array


To determine the size of the array in bytes, we can use sizeof operator.
size_t is the type returned by the sizeof operator and is widely used in the standard
library to represent sizes and counts.

Ex: int a[17];


size_t n=sizeof(a);
if int occupies 2 bytes length, then n is 34.
To determine the lenth of the array or number of elements in the array ,we can
divide the total size of the array by the size of the array element.
Ex: int a[17];
size_t n;
n=sizeof(a)/sizeof(int); or n=sizeof(a)/sizeof(a[0]);
i.e n=34/2=17.

Department of Computer Science 11 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Following example shows calculating array length.


#include<stdio.h>
#include<stdlib.h>
void main()
{
int arr[30],length;
size_t n;
n=sizeof(a);
length = n/sizeof(int);
printf("length of thr array is = %d",length);
getch();
}
Operations that can be performed on array
Following operations can be performed on arrays.
1. Displaying or Accessing Array Elements
2. Performing arithmetic operations an Array elements
3. Sorting array Elements
4. Searching for Array elements
5. Insertion and Deletion
6. merging
1. Displaying:
We can process all the elements of the array.
#include <stdio.h>
Void main()
{
int a[10];
printf("Enter array elements: ");
for(int i = 0; i < 10; ++i)
scanf("%d", &a[i]);
printf("array elements are \n: ");

Department of Computer Science 12 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

for(int i = 0; i < 10; ++i)


printf("%d\t", values[i]);
getch()
}
a[0] a[1] a[2] …………………………………a[9]
10 20 30 100

Displays as follows
10 20 30 40 ……………………… 100

2. Performing Arithmetic Operations:


We can perform all arithmetic operations an Array elements.
EX: int a[5]={2,4,8,3,6};
c=a[0]+a[2];
c=2+8=10.
d=a[1]*a[3];
d=4*3=12.
Ex: a[4]+ +;
a[4]=6++=7
a[3]--=3--=2

3. Sorting array elements


Array elements can be arranged either in ascending or descending order.
Ex: int a[10]={2,6,10,3,4,18,12,11,14,5}.
After sorting
Array in ascending order:2 3 4 5 6 10 11 12 14 18
Array in ascending order:18 14 12 11 10 6 5 4 3 2

Department of Computer Science 13 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

/* * C program to accept N numbers and arrange them in an ascending order */


#include <stdio.h>
void main()
{
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
for (j = i + 1; j < n; ++j)
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);
}

4. Searching for an array element


We can search an array for a particular element.
Ex: int a[6]={13,50,16,28,33,43};
a 13 50 16 28 33 43
If required elements is 16
‘16’ is located at position a[2];

Department of Computer Science 14 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

If required element is 85
Element not found in the array.
Ex: Searching for an element
#include <stdio.h>
void main()
{
int a[100], n, i,el;
int flag;
clrscr();
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter Array elements:”);
for (i = 0; i< n; i++)
scanf("%d", &array[i]);
printf("Enter a number to search:");
scanf("%d", &el);
for (i = 0;i < n;i++)
{
if (a[i] == el)
{
flag==1;
break;
}
}
if (flag ==1)
printf(“elements is found”);
else
printf({“element is not found”);
getch();
}

Department of Computer Science 15 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

5. Inserting and Deleting Array elements


We can insert new element into an existing array
Ex: int a[10]= {3,6,9,10,12};

a 3 6 9 10 12 - - - - -
0 1 2 3 4 5 6 7 8 9
Inserting element 8 after 9 will rearray gets as shown

a 3 6 9 8 10 12 - - - -
0 1 2 3 4 5 6 7 8 9
Similarly we can delete an element from the array.
Ex:
If int a[6]={8,9,10,4,7,12};
a 8 9 10 4 7 12
0 1 2 3 4 5
After deleting an element ‘4’ from array
a 8 9 10 7 12 --
0 1 2 3 4 5

6. Merging Arrays:
We can merge arrays i.e we can append second array form the last element of the
first array.
Ex: int a[10]={4,5,6,7};
Int b[6] ={8,9,10,11};
After merging ‘b’ with ‘a’, array a become
a 4 5 6 7 -- -- -- -- -- --
0 1 2 3 4 5 6 7 8 9
b 8 9 10 11 -- --
0 1 2 3 4 5

Department of Computer Science 16 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

After merging

a 4 5 6 7 8 9 10 11 -- --
b 8 9 10 11 -- --
0 1 2 3 4 5 6 7 8 9

Character Arrays

A set of characters may be stored in an array.

Declaration : A Character array can be declared as shown below.


char array_name[size of an array];

Ex : char name [20];


The above statement declares ‘name’ as an character array and allows to store
upto 20 characters.

Ex : main ()
{
char word [ ] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’ , ‘!’};
int i;
for(i=0; i<10; i++)
printf(“%c”, word[i]);
getch();
}

In above program ‘word’ is the character array. The C language allows to


define an array without specifying the number of elements. The size of the array is
automatically based on the number of initialisation elements. In the above example
a character array of size 6 will be created and each element is initialised with
respective values as shown below

word
H e l l o !
word[0] word[1] word[2] word[3] word[4] word[5]

The for loop displays each character in the array and output will be “Hello!”

Department of Computer Science 17 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Program to sort characters in an array :

#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
int i,j;
char temp;
printf("Enter characters :");
for(i=0;i<10;i++)
scanf("%c",&str[i]);
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(str[i]>str[j])
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
}
}
printf("\nAfter sorting:\n”);
for(i=0;i<10;i++)
printf(“%c”,str[i]);
getch();
}

The const Qualifier : ‘const’ qualifier is associated with variable whose value will
not be changed by the program. Using ‘const’ qualifier, we can tell the complier that
the specified variable has a constant value throughout the program’s execution.

Ex : const double pi = 3.141592654;

The above statement declares the const variable pi. If we try to assign a value
to a ‘const’ variable after initialising it, the complier might issue an error message.
The complier places the ‘const’ variables into read-only memory.

Ex : const float pi = 30141593;

Pi=pi/2 ; will give an error as variable ‘pi’ is declared as const variable.

Department of Computer Science 18 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

One dimensional array for inter function communication:

When a function gets executed in the program, the execution control is


transferred from calling function to called function and executes function definition,
and finally comes back to the calling function. In this process both calling and called
functions have to communicate with each other to exchange information.

Array elements and array itself can be used in inter function communication.

Passing Array elements to a Function:

Like an ordinary variables and values, it is also possible to pass the value of an array
element and even an entire array as an argument to a function.

To pass a single array element to a function, the array element is specified as


an argument to the function in the normal way.
Ex : main
{
float sample [10];
int i;
for(i=0; i<10; i++)
scanf (“%f”, & sample[i]);
disp(sample[0], sample[1]);
getch();
}

void disp(float x, float y)


{
printf(“/n First Element of array :%f”,x);
printf(“/n Second Element of array :%f”,y);
}

In the above example the function disp() is called by passing first two
elements of an array as arguments and are received in similar type of arguments.

To pass an array to a function, it is only necessary to list the name of the array,
without any subscripts, inside the call to the functions.

Department of Computer Science 19 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Ex : main ()
{
int gradescores [100];
int minscore;
….. ….. ….
….. ….. ….
minscroe = minimum (gradescores);
}
int minimum (int values [100])
{
…… ……. ……
…… …….. ……
return (min value);
}

In the above examples the declaration defines the function minimum () as


returning a value of type int and taking as its argument an array containing 100
integer elements. References made to the formal parameters array ‘values’ reference
the appropriate elements inside the array that was passed to the function.
Passing entire array as argument
An array can easily passed to a function by using its pointer.

Ex : main ()
{
int a[50];
int *p1, i,n;
printf(“\n Enter no.of elements :”);
scanf(“%d”,&n);
printf(“\n Enter array elements :”);
for (i=0; i<n;i++)
scanf (“%d” & a[i]);
p1=&a[0];
display (p1,n);
getch();
}
void display (int *p2, int n)
{
int i;
for (i=0; i<n;i++)
{
printf(“\t %d”, * p2);
p2++;
}
}

Department of Computer Science 20 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

In the above program array pointer and no.of elements in array are passed to
function display (). In function the arguments are received into formal arguments
(i) an integer pointer (ii) and integer value. The for loop in the function display ()
will access the array elements of array ‘a’ declared in main () using pointers.

Variable – Length Arrays

Variable length arrays enables us to work with array without giving a constant size.

Ex : int a[20];

In this example the size of an array is declared to be of a specific size. But if


we want store 100, 500 or more elements, we need to redefine the array. The ‘C’
language allows to declare arrays of a variable size.

Ex : main ()
{
int size, i;
float sample[size];
printf(“Enter the size:”);
scanf(“%d”, &size);
for(i=0; i<size; i++)
scanf(“%f”, & sample[i]);
prinf(“Array Elements are:\n”);
for(i=0; i<size; i++)
printf(“\t%f”, sample[i]);
getch();
}

In the above example the array sample is declared to contain ‘size’ elements.
This is called a variable length array because the size of the array is specified by a
variable and not by a constant expression.

Multi dimensional Arrays

Two dimensional Arrays:

A two-dimensional array can be visualized as a table of rows and columns


where each element is identified by unique row and unique column number. Such
an arrangement usually referred to as a matrix.

Declaration of two-dimensional array:

The general form of declaring two-dimensional array is

Department of Computer Science 21 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

data type array_name [row-size] [column-size];

Where row-size refers to no. of rows and column-size refers to no. of columns.
Each dimension of the two dimensional array is indexed from zero to its maximum
size minus one. The individual elements of a two dimensional array can be referred
by two indexes (or) subscripts. The first index selects the row and the second index
selects the column within that row. The individual elements of the two dimensional
array will be stored in continuous memory locations.

Ex: int a[5][5];


This defines ‘a’ as a integer array having 5 rows and 5 columns i.e., 5x5=25
elements.

a[0][0] a[0][1] …………………………………………………………………a[4][4]

The two dimensional array elements can be viewed as matrix


a00 a01 a02 a03 a04
a10 a11 a12 a13 a14
. . .
. . .
. . .
. . .
. . .
a40 a41 a42 a43 a44
Ex: char page[24][80];
float month[12][15];

Initialization of two-dimensional arrays:


Two-dimensional arrays may be initialised by following their declaration
with a list of initial values enclosed in braces.

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

This initialises the elements of the first row to zero and the second row to one.
The above statement can be written as
int table[2][3]={{0,0,0}, {1,1,1}};
(or)
int table[2][3]={
{0,0,0},
{1,1,1},
};

Department of Computer Science 22 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

While initialising a two-dimensional array it is necessary to mention the second


dimension, whereas the first dimension is optional.

The following statements are acceptable.


int arr[2][3]={12, 34, 23, 45, 56, 45};
int arr[ ][3]={12, 34, 23, 45, 56, 45};

But the following statements are not acceptable.


int arr[2][ ]={12, 34, 23, 45, 56, 45};
int arr[ ][ ]={12, 34, 23, 45, 56, 45};

Important points regarding initialisation of an array at the time of declaration.

1. The size of an array can be omitted in the declaration. If the size is


omitted, then the compiler will reserve the memory location
corresponds to number of individual elements that includes in the
declaration.
2. If the array elements are not given any specific values, they will
contain garbage values.

3. ‘C’ will not allow to specify repetation of an initialisation, (or) to


initialise an element in the middle of an array with-out supplying all
the preceding values.

** Initialisation of arrays in C suffers two drawbacks.

1. There is no convenient way to initialise only selected elements.


2. There is no shortcut method for initialising a large number of array
elements.

Assigning values to two-dimensional array elements:

Values to two dimensional array elements can be assigned by using loops.


Ex: main()
{
int a[3][3];
int i,j;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
scanf(“%d”, &a[i][j]);
}
}
Two for loops can be used to assign values to independent elements of an array.

Department of Computer Science 23 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Elements of two dimensional array can be accessed individually.

Ex: a[0][0]=25;
scanf (“%d”, & a[0][0]);

Ex: Program using Two Dimensional Arrays

#include<stdio.h>
#include<conio.h>
main()
{
int a[10][10],i,j,r,c;
clrscr();
printf("Enter order of matrix:");
scanf("%d%d",&r,&c);
printf("Enter %d values",r*c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
printf("\nElements of array a:");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",a[i][j]);
}
}
getch();
}

OUTPUT
Enter order of matrix:2 2
Enter 4 values1
2
3
4
Elements of array a:
1 2
3 4

Department of Computer Science 24 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Operations on Two Dimensional Arrays

Note : Write about the following

1. Declaration of Two Dimensional Array


2. Assign values to two Dimensional Arrays
3. All operations explained for One Dimensional arrays with two dimensional
array declarations
4. Matrix Addition, Subtraction, Multiplication, Transpose etc.

Character Strings
Array of Characters:

To hold more than a single character, an array of characters can be used. A


character array can be declared as

char arrayname [size];

Ex :- char word[6] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘!’};

This statement reserves space in memory for six characters, as shown in


fig. below.

‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘!’


word[0] word[1] word[2] word[3] word[4] word[5]

The values to character array may be assigned using loops.

Ex:- char name[10];


int i;
for(i = 0 ; i < 10; i ++)
scanf(“%c”,&name[i]);

The above loop assigns character by character to array called ‘name’.

To print out the contents of the array ‘name’, we can run through each
element in the array and display it using the %c format characters.

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


printf(“%c”,name[i]);

Department of Computer Science 25 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Variable Length Character Strings

A group of characters is called a string. There is no string built-in data type in


‘C’. Character arrays can be used to store strings. A string constant may be an array
of characters terminated by a null character (‘\0’).

Ex: COMPUTER would be stored as

C O M P U T E R \0

The length of a string is the number of characters it contains excluding null


character. Hence, the number of locations needed to store a string is one more than
length of string. A string not terminated by a ‘\0’ is not really a string, but a
collection of characters.
Declaring and initialising string variables:

The general form of declaration of string variable is:

char string_name[size];

Where string_name is the name of the string and size is the size of the string.

Ex: char name[30];


char designation[25];

String variables can be initialised at the time of declaration.

Ex: char name[30]=”vijay”


char name[30]={ ‘T’, ‘C’, ‘S’, ‘\0’ }
char name[ ] =”TCS”;
char name[ ]={ ‘T’, ‘C’, ‘S’, ‘\0’}
A string variable can also be initialised to null string as

char A[10]=” “;

scanf() and gets() functions are used to input values to string variables. printf() and
puts() functions are used to output values of string variables.

Input using scanf():

Scanf() function can be used to assign value to a string variable. By using scanf(),
multiword strings can’t be assigned to variables.

Department of Computer Science 26 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Ex: char sname[20];


scanf(“%s”,sname);

Output using printf():

The function printf() can be used to display a string variable.

Ex: printf(“%s”,sname);

Ex:
#include “stdio.h”
#include “conio.h”
main()
{
char name[25];
printf(“Enter name:\n”);
scanf(“%s”, name);
printf(“The name is: %s”, name);
getch();
}
Input using gets():

The function gets() is used to assign multiword values to string variables.


gets(variable name);

Ex: gets(name);

gets() can be used to read only one string at a time.

main()
{
char str[20];
gets(str);
printf(“%s”, str);
getch();
}

Output using puts():

puts() is used output string variables.


puts(variable name);

Ex: puts(name);
puts (“strings”);

Department of Computer Science 27 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Above statement displays value of string variable name on monitor puts() can
output only one string at a time. puts() places the cursor automatically on the next
line.

Ex: main()
{
char name[25];
gets(name);
puts(name);
getch();
}

String Functions

String handling library functions are contained in the header file string.h. The
following list shows the more commonly used functions.

Function Meaning
strlen() Finds length of a string
strlwr() Converts a string to lower case
strupr() Converts a string to uppercase
strcat() Appends one string at the end of another
strncat() Appends first ‘n’ characters of a string at the end of another.
strcpy() Copies a string into another
strncpy() Copies first ‘n’ characters of one string into another
strcmp() Compares two strings
strncmp() Compares first ‘n’ characters of two strings
strchr() Finds first occurrence of a given character in a string.
strrchr() Finds last occurrence of a given character in a string.
strstr() Finds first occurrence of a given string in another string
strset() Sets all characters of string to a given character
strnset() Sets first n characters of a string to a given character
strrev() Reverses a string.

Department of Computer Science 28 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

strlen():

This function return the length of the string i.e. the number of characters in the
string.

Ex: int c;
char name[20] = “location”;
c = strlen(name);
The above statement returns ‘8’ and assigns to C.

strcmp():

This function is used for comparison of two strings. If two strings are equal
strcmp() would return a value 0, otherwise it would return a non-zero value. This
function compares the string character by character.

Ex: char str1[20], str2[20];


strcmp(str1, str2)
returns value
0 str1 == str2
>0 str1 > str2
<0 str1 < str2

Ex : char str[20] = “value”;


char str2[20]=”class”;
strncmp(str1, str2);
returns>0 since
str1> str2.

strncmp():

This function compares first ‘n’ characters of two strings.

strncmp(str1, str2, 4)

This function compares first 4 characters of str1 and str2 and returns 0 if they
equal and non zero if they are not equal.

Ex: char str1[10]=”college”;


char str2[10]=”comission”;

Department of Computer Science 29 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

int c;
c = strncmp(str1, str2, 3);

This statement returns < 0 and assigns to C, since characters of str2 is large
than characters of str1.

strcpy():

This function is used for copying of one string to another string.

Ex: strcpy(str1, str2);

This function copies str2 to str1.

str2 is the source string and str1 is destination string.


Ex: char str1[10] = “copy”;
char str2[10];
strcpy(str2, str1);
Now both str1, str2 contains the string “copy”.

strncpy():

This function is copies first ‘n’ characters of a string to another string.


strncpy(str2, str1, 5);
This function copies first 5 characters of str1 to str2.

Ex: char str1[20] = “college”;


char str2[20];
strncpy(str2, str1, 5);
After the execution of above function str2 contains “colle”.

strcat():

This function is used for concatenation of two strings.

Ex: strcat(str1, str2);

This function concatenates str2 at the end of str1.

Ex: char str1[20] = “This is a”;


char str2[10] = “college”;
strcat(str1, str2);

After above statement str1 contains the string “This is a college”.

Department of Computer Science 30 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

strncat():

This function concatenates first ‘n’ characters of a string to another string.

strncat(s1, s2, 4);

This function concatenates the string str1 with first 4 characters of s2.

Ex: char str1[20] = “This is ”;


char str2[20] = “a system”;
strncat(str1, str2, 5);

After the execution of above function string s1 contains “This is a sys”.

strrev():

This function is used for reversing all characters of the strings.

Ex: main()
{
char arr[25];
gets(arr);
strrev(arr);
printf(“\n String after reverse: %s”, arr);
}

The above program displays the string in reverse order.


If arr = “college”, The program displays “egelloc”.

strupr():

This function coverts all characters of the string into uppercase.

Ex: main()
{
char arr[25];
gets(arr);
strupr(arr);
printf(“\n After conversion: %s”, arr);
}

The above program displays the string in uppercase.

If arr = “college”, The program displays “COLLEGE”.

Department of Computer Science 31 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

strlwr():

This function converts all characters of the string into lowercase.

Ex: strlwr(str1);

Converts the string str1 characters into lowercase.

strstr():

This function is used to find the occurrence of the given string in another
string.

Ex: strstr(str1, str2);

Returns a pointer to the first occurrence of str2 in str1.


Ex: char str1[20] = “This is a program”;
char str2[20] = “is”;
strstr(str1, str2);
The above function returns “is a program”.

strchr():

This function is used to find the first occurrence of a given character in a


string.

Ex: strchr(s1, ch1);

Returns a pointer to the first occurrence of ch1 in s1.

Ex: char s1[20] = “education is excellent”;


strchr(s1, ‘c’);

This function returns “cation is excellent”.

strrchr(): This function finds the last occurrence of a given character in a string.

strset():

This function is used to set a all characters of a string to a given character.

Ex: strset(str1, “k”);

Set all characters of the string str1 to a character ‘k’.

Department of Computer Science 32 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Ex: char s1[20] = “system”;


strset(s1, ‘s’);

After execution of the above function s1 contains “ssssss”.

strnset():

This function sets the first ‘n’ characters of the string to a given character.

Ex: strnset(s1, “c”, 4);

This function sets first four characters of s1 to cccc.

Escape Characters

The combination of backslash and some characters can be used to perform


special functions. These various backslash characters, often referred to as escape
characters. Table below shows different escape characters.

Escape Character Name


\a Audible alert
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\” Double quotation mark
\’ Single quotation mark
\? Question mark
\nnn Octal character value nnn
\unnnn Universal character name
\Unnnnnnnn Universal character name
\xnn Hexadecimal character value nn

The first seven characters listed in the table perform the indicated function on
most output devices when they are displayed. The audible alert character, \a,
sounds a “bell” in most terminal windows.

Ex : printf( “ \a SYSTEM SHUT DOWNIN 5 MINUTES \n ”);


sounds an alert and displays the indicated message.

Department of Computer Science 33 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

Including the backspace character ‘\b’ inside a character string causes the
terminal to backspace one character at the point at which the character appears in
the string, provided that it is supported by the terminal window.

The statement

printf(“ %i \t %i \t %i \n”, a,b,c);

displays the value of a, spaces over to the next tab position, displays the value
of b, spaces over to next tab position, and then displays the value of C. The
horizontal tab character is particularly useful for lining up data in columns.

To include the backslash character itself inside a character string, two


backslash characters are necessary.

prinft(“\\t is the horizontal tab character\n”);


gives output : \t is the horizontal tab character.

To include a double quotation character inside a character string, it must be


preceded by a backslash.

printf(“\”Hello\” ”);
prints the message “Hello”
c=’\’; assigns a single quotation to variable ‘c’.

In the escape character ‘\nnn\, nnn is a one-to-three-digit octal number.


In ‘\xnn’, nn is a hexadecimal number.

Character strings, structures and Arrays

The basic elements of the C programming language can be combined to form


very powerful programming constructs in many ways. Structures, arrays and
variable –length character strings may be combined. Array of structures, combined
with the variable- length character strings.

Ex : struct book
{
char bookname [20];
char publisher [30];
};

In the above definition a structure consisting of two strings bookname and


publisher is declared.

Department of Computer Science 34 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

struct book book1 = {“C Fundamentals”, “Macgraw hill”};

Defines a variable book1 of type struct book and initialises bookname and
publisher to the specified values.

The variable book1 can be accessed as book1.bookname, book1.publisher. To


assign values either scanf() or gets() can be used.

Ex : scanf(“%s”, book1.bookname);
Scanf(“%s”,book1.publisher);

Ex: gets(book1.bookname);
scanf(book1.bookname);

An array of structures may declared as


struct book book2[10];

This definition declares an array book2 of type struct book and consists 10
elements. Following example illustrates array of structures combined with strings.

main()
{
struct book
{
char bookname[20];
char publisher[30];
};
struct book book1[10];
int i;
clrscr();
printf(“Enter books detail:\n”);
for (i = 0; i < 10; i++)
{
printf(“\n Enter Book No : “);
gets(book1[i].bookname);
printf(“\n Enter Publisher:”);
gets(book1[i].publisher);
}
printf(“\n Books Details \n”);
for(i = 0; i < 10; i++)
{
printf(“\n Book Name : %s”, book1[i].bookname);
printf(“\n Publisher :%s”, book1[i].publisher);
}

Department of Computer Science 35 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

getch();
}

In the above program variable book1 is declared as array of type struct book.
The first for loop will assign values to array elements. The second for loop displays
the array elements. Since each array element is structure they can be accessed as

book1[0].bookname, book1[0].publisher
book1[1].bookname, book1[1].publisher and so on.

Character Operations

Character variables and constants are frequently used in relational and


arithmetic expressions. Whenever a character constant or variable is used in an
expression in C, it is automatically converted to, and subsequently treated as, an
integer value.

Ex : C1> = ‘a’ && C1> = ‘z’

Could be used to determine if the character variable ‘C1’ contained a


lowercase letters. In computer system the lowercase letters are represented
sequentially in ASCII, with no other characters in – between.
The above expression compares ASCII value of C1 with ASCII value of a. In
ASCII character ‘a’ has the value 97, ‘b’ has 98 and so on. So C1> = ‘a’ is TRUE, for
any lower case letter contained in C1, because it has a value that is greater than or
equal to 97.

The expression
C1 > = ’a’ & & C1< = ’z’ could by replaced by C1>=97 && C1<=122, if ‘C1’ is
lowercase letter.

Ex : printf(“%i", ’a’) will display 97.


printf(“%i”, C1) will display ASCII value of a character that is internally
stored in C1.

Ex : The character ‘0’ is not same as the integer 0, the character ’1’ is not same
as the integer1, and so an.

Program to illustrate conversion of string to integer :

#include “stdio.h”
main()
{
char str[10];

Department of Computer Science 36 A.S.N. Degree College, Tenali


Programming using C UNIT-III I B.C.A

int value, i;
int result=0;
printf(“\n Enter String:”);
scanf(“%s”, str);
for(i=0;str[i]>=’0’ && str[i]<=’9’; i++)
{
value = str[i]-‘0’;
result=result*10+value;
}
printf(“\n Integer value : %d”, result);
}

Character Functions in C

“ ctype.h”, header file support all the below character functions in ‘C’.

Function Description
isalpha() This function checks whether character is
alphabet
isdigit() This function checks whether character is
digit
isalnum() This function checks whether character is
alpha-numeric
isspace() This function checks whether character is
space
islower() This function checks whether character is
lowercase
isupper() This function checks whether character is
Uppercase
isxdigit() This function checks whether character is
hexadecimal
iscntrl() This function checks whether character is
a control character
isprint() This function checks whether character is
a printable character
ispunct() This function checks whether character is
a punctuation
isgraph() This function checks whether character is
a graphical character
tolower() This function checks whether character is
alphabetic & converts to lower case
toupper() This function checks whether character is
alphabetic & converts to upper case

Department of Computer Science 37 A.S.N. Degree College, Tenali

You might also like