0% found this document useful (0 votes)
19 views30 pages

Unit - Iii Iterative Control Statements: Arrays

The document discusses iterative control statements, arrays, and strings. It covers topics like loops, nested loops, break and continue statements, arrays, one and two dimensional arrays, and string operations and functions.

Uploaded by

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

Unit - Iii Iterative Control Statements: Arrays

The document discusses iterative control statements, arrays, and strings. It covers topics like loops, nested loops, break and continue statements, arrays, one and two dimensional arrays, and string operations and functions.

Uploaded by

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

UNIT – III

Iterative Control Statements, Arrays and Strings


UNIT - III
Iterative Control Statements:
Iterative Statements – Nested Loops – Break and Continue Statement - Goto Statement
Arrays:
Introduction – Declaration of Arrays – Accessing elements of the Array – Storing Values in Array –
one dimensional array for inter-function communication – Two dimensional Arrays – two dimensional
arrays for inter-function communication
Strings:
Introduction – String operations – String functions

Iterative Control Statements:


Looping Statements:
When a single statement or a group of statements executing again and again in a program i.e.
in an iterative way, such type of processing is called Loop. These are classified into two parts:
a. body of the loop
b. control of the loop
The control loop statements tests certain conditions and then directs the repeated execution
of the statements contained in the body of the loop. Mainly control loop are categorized into two parts:
They are:
1. Entry control loop
2. Exit control loop
1. Entry control loop:
In an entry control loop, first the condition is checked, if it is true, then body of the loop is
executed otherwise the control is moved out of the loop i.e. we can exit from the loop when the condition
becomes false.
Entry control loop is also called base loop. The “while” and “for” are the examples of entry
control loop. The flow chart is as shown below:

conditi
on NO

YES

Body of the loop


Statement
(true statement block)

2. Exit control loop:


In an exit control loop, first body of the loop is executed and then condition is checked. If the
condition is true, then again the body of the loop is executed. If the condition is false, then control will
move out from the loop.
Exit control loop is also called derived loop. The “ do-while “ statement is an example of exit control
loop. The flow chart is shown below:

1|P ag e
Body of the loop

NO conditi YES
on

Statement

1. while loop (or) while statement:


The while loop is an entry control loop. In this, first condition is checked and if it true then
body of the loop is executed, It will execute again and again till the condition is false.
The syntax is:
while(condition)
{
body of the loop(statements);
}
statements;
The flowchart is:

conditi
on NO

YES

Body of the loop


Statement
(true statement block)

Ex:/*program for reverse of a number */


#include<stdio.h>
#include<conio.h>
void main ()
{
int r,n,rev=0;
clrscr();
printf(“Enter value of n:”);
scanf(“%d”,&n);
while(n>0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
}
printf(“\nReverse is %d”,rev);
getch();
}

2|P ag e
2. do-while loop (or) do-while statement:
The do-while loop is an exit control loop. In this, first body of the loop is executed and then
the condition is checked. If the condition is true, then the body of the loop is executed. If the
condition is false, then it will exit from the loop.
The syntax for do-while loop is:
do
{
body of the loop(statements);
}while(condition);
statements;

Flowchart is:

Body of the loop

NO Conditi YES
on

Statement

Ex:/*program for reverse of a number*/


#include<stdio.h>
#include<conio.h>
void main()
{
int r,n,rev=0;
clrscr();
printf(“Enter value of n:”);
scanf(“%d”,&n);
do
{
r=n%10;
rev=rev*10+r;
n=n/10;
}while(n>0);
printf(“\n reverse is %d” ,rev);
getch();
}

3. for loop (or) for statement :


for loop is an entry control looping statement which repeats again and again till the condition
is satisfied.
It is a one step loop, which ‘initialize’, ‘check the condition and then ‘increment / decrement’.

3|P ag e
The syntax is :
for(initial value; test condition; increment/decrement)
{
body of the loop(statements);
}
statements;
The flowchart is:
initialization

conditi
on
NO

YES

Body of the loop Statement


(true statement
block)
In the above for loop, first the value is initialized, then in the loop the test condition is checked and
further the loop will increment/decrement according to the requirement. After completion of the loop, i.e.
when the condition becomes false then the statement will be executed.
Ex:/*program to print 1 to 10 numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int I;
clrscr();
printf(“the numbers from 1 to 10 are:”);
for(i=1;i<=10;i++)
{
printf(“%d\n”,i);
}
getch();
}
Nested for:
When a for loop is executed within another for loop then it is called nested for loop. In this first
the inner loop will be completed then the outer loop will be completed later according to the condition.
The syntax is:
for(initial value-1; test condition-1; increment-1/decrement-1)
{
for(initial value-2; test condition-2; increment-2/decrement-2)
{
Inner body of the loop(statements);
}
Outer body of the loop(statements);

4|P ag e
}
Statements;
Ex:/*program to illustrate nested for loop*/
#include<stdio.h>
#include<conio.h>
void main()
{
int I,j,n;
clrscr();
printf(“Enter value of n:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++);
{
printf(“%d”,j);
}
printf(“\n”);
}
getch();
}
Output: Enter value of n 3
1
12
123

JUMPING STATEMENTS:
The jumping statements are categorized into three different controls which are used to jump
a statement from one to another in a program and make the execution of he programming procedure fast.
The three jumping controls are:
1. goto statement
2. break statement
3. continue statement
1. goto statement:
The goto statement moves the controls on a specified address called “label“. The goto is
classified into two types. They are conditional and unconditional which can be either forward or backward
direction depending on the program requirement.
The different types of goto are:

forward goto backward goto

with condition without condition with condition without condition

5|P ag e
1. forward goto statement :
a. forward goto without condition:
The syntax for forward goto without condition statement is:
Statement-1;
Statement-2;
goto label;
Statement-3;
Statement-4;
Label:
Statement-5;
Statement-6;
Ex: /*program for unconditional forward goto */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf(“Enter a and b values:”);
scanf(“%d%d”,&a,&b);
c=a+b;
goto add;
goto minus;
add:
printf(“\nsum is %d”,c);
subtract:
c=a-b;
printf(“\nminus is%d”,c);
}
b. forward goto with condition:
The syntax for forward goto with condition statement is:
Statement-1;
condition()
goto label;
Statement-3;
Label:
Ex: /*program for conditional forward goto */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(“Enter a and b values:”);
scanf(“%d%d”,&a,&b);
if(x>y)
goto output1;
else

6|P ag e
goto output2;
output1:
printf(“\nmaximum is %d”,x);
output2:
printf(“\nmaximum is %d”,y);
goto stop;
stop:
getch();
}
2. backward goto statement :
a. backward goto without condition:
The syntax for backward goto without condition statement is:
Statement-1;
Statement-2;
Label:
Statement-3;
Goto Label;
Statement-4;
In this first the statement-1, statement-2 and statement-3 will be executed. Then it
will find a goto label so that it will go to a specified label and again the statements are executed
repeatedly creating a infinite looping.
b.backward goto with condition:
The syntax for backward goto with condition statement is:
Statement-1;
Label:
Statement-2;
Condition()
goto label;
Statement-3;
Ex: /*program to find square root of a number */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b;
clrscr();
start:
printf(“Enter value of a:”);
scanf(“%d”,&a);
if(a<0)
goto start;
b=sqrt(a);
printf(“\n square root of %d is %d”,&a,&b);

7|P ag e
2. break statement:
Break statement always used with the decision-making statements like if and switch
statements. The statement will quit from the loop when the condition is true.
The syntax for break statement is:
break;
The statement is used within any of the looping statements.
while statement:
while(condition-1)
{
statement;
if(condition-2)
{
break;
}
} statement;

do-while statement:
do
{
statement-1;
if(condition)
{
break;
}
}while(condition);
statement-2;
for statement:
for(initial value; test condition; increment/decrement)
{
if(condition)
{
break;
}
}
statement;
Ex:/*program to print sum of n positive numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,num,n,sum=0;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&num);
printf(“Enter the numbers:”);

8|P ag e
for(i=0;i<=n;i++)
{
scanf(“%d”,&n);
if(n<0)
break;
sum+=sum;
}
printf(“Sum of positive numbers is:%d”,sum);
getch();
}
Output: enter a number 4
Enter the numbers:4
5
-2
Sum of positive numbers is 9
3. continue statement :
The continue statement will skip some part of iteration and comes to the next looping step.
The syntax for continue statement is:
continue;
The statement is used within any of the looping statements.
while statement:
while(condition-1)
{
Statement;
if(condition-2)
{
continue;
}
}
Statement;
do-while statement:
do
{
Statement-1;
if(condition)
{
continue;
}
Statement-2;
}while(condition);
Statement-3;
for statement:
for(initial value; test condition; increment/decrement)
{
Statement-1;

9|P ag e
if(condition)
{
continue;
}
Statement-2;
}
Statement-3;
Ex:/*program to print sum of n positive numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int I,num,n,sum=0;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&num);
printf(“Enter the numbers:”);
for(i=0;i<=n;i++)
{
scanf(“%d”,&n);
if(n<0)
continue;
sum+=sum;
}
printf(“Sum of positive numbers is:%d”,sum);
getch();
}
Output: enter a number 4
Enter the numbers:4
5
-2
1
Sum of positive numbers is 10

Arrays:
program to accept & display 5 students marks*/
#include<stdio.h>
#include<conio.h>
void main()
{
int m1=65,m2=55,m3=80,m4=90,m5=67;
printf("1st student marks are :%d\n",m1);
printf("2nd student marks are :%d\n",m2);
printf("3rd student marks are :%d\n",m3);
printf("4th student marks are: %d\n",m4);
printf("5th student marks are: %d\n",m5);

10 | P a g e
getch();
}
Output:
1st student marks are :65
2nd student marks are :55
3rd student marks are :80
4th student marks are: 90
5th student marks are: 67
In the above program, to display 5 students marks we have declared 5 variables and 5 printf
statements to display it. Suppose assume it for the students of 100, then we have to take 100 variables to
store marks obtained by 100 different students and 100 printf statements or a single printf statement
containing these all variables. One common organizing technique is to use arrays in such situations. We can
declare one variable, which is capable of holding all the 100 students marks.
Use of Arrays
 Storing more than one value at a time under a single name.
 Reading, processing and displaying the array elements is far easier
Definition of Array:
Arrays are variables that are capable of having more than one value at a time. “An array is a
collection of homogenous elements of same data type stored in adjacent locations.” The same data type
could be all ints (or) floats (or) chars etc…
Syntax:
datatype array_name[size];
size is the maximum number of elements that can be stored in the array.
Ex: int a[100]
float rates[5];
char name[20];

Arrays are of 3 types:-


1. One Dimensional Array
2. Two Dimensional Array
3. Multi-Dimensional Array
Declaration of 1-D Array:
Ex: int a[10];
The above statement tells the compiler to reserve sufficient amount of space to store 10 integers
and specify a name ‘a’ to the entire collection.
Organization of elements in memory:
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
Elements 26 14 83 37 46 52 18 12 54

Index 0 1 2 3 4 5 6 7 8
Addresses 100 102 104 106 108 110 112 114 116

The index begin with 0 and ends with one less than the size of the array.
The array elements are accessed by its position in the group is called subscript or index.

11 | P a g e
Initialization of 1-D Array:
Like a variable an array can also be initialized at the time of declaration.
int num[5]={1,2,3,4,5};
To access the number 3 we can simply write a[2]
int digits[ ] = {1,2,3,4,5,6,7,8,9,10};
char name[5]={‘e’,’i’,’o’,’u’,’a’};
float rate[3]={20.5,34.5,67.9};
//program to accept and display the array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],n,i;
printf("How many nos do u want to enter:");
scanf("%d",&n); //size of the array
printf("Enter the Numbers:");
for(i=0;i<n;i++)
scanf("%d",&a[i]); //reading elements into the array
printf("The elements in the array are...");
for(i=0;i<n;i++)
printf("%d\t",a[i]); //displaying the elements in the array
getch();
}
Output:
How many nos do u want to enter:5
Enter the Numbers:1
2
3
4
5
The elements in the array are...1 2 3 4 5

//Program to read and display the array in reverse


#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],n,i;
printf("How many nos do u want to enter:");
scanf("%d",&n); //size of the array
printf("Enter the Numbers:");
for(i=0;i<n;i++)
scanf("%d",&a[i]); //reading elements into the array
printf("The elements in the array are...");
for(i=n-1;i>=0;i--)
printf("%d\t",a[i]); //displaying the elements in the array in reverse order

12 | P a g e
getch();
}
Output:
How many nos do u want to enter:5
Enter the Numbers:1
2
3
4
5
The elements in the array are...5 4 3 2 1

//Program to find the sum of array elements


#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],sum=0,n,i;
clrscr();
printf("Enter the size of array:");
scanf("%d",&n);
printf("\nEnter the elements into the array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
sum=sum+a[i];
printf("\nThe sum of the array elements are...%d",sum);
getch();
}
Output:
Enter the size of array:5
Enter the elements into the array:1 2 3 4 5
The sum of the array elements are...15

Sorting:
Sorting is the technique, which arranges all the elements in the array in increasing or in decreasing order.
There are many sorting techniques some of them are Bubble Sort, Selection Sort, Insertion Sort, Merge
Sort, Quick Sort etc.
Bubble Sort:
Step-by-step example
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number
using bubble sort algorithm.
First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not

13 | P a g e
swap them.
Second Pass:
(14258) (14258)
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2
(12458) (12458)
(12458) (12458)
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs
one whole pass without any swap to know it is sorted.
Third Pass:
(12458) (12458)
(12458) (12458)
(12458) (12458)
(12458) (12458)
Finally, the array is sorted, and the algorithm can terminate.
//Program for Bubble Sort
#include<stdio.h>
void main()
{
int a[10],n,i,j,t;
clrscr();
printf("How many numbers:");
scanf("%d",&n);
printf("Enter the numbers :");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("The sorted list ...");
for(i=0;i<n-1;i++) //for ‘n’ elements n-1 passes
{
for(j=0;j<n-1-i;j++) //and each time n-1-I comparisons
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
for(i=0;i<n;i++)
printf("\n\t\t%d",a[i]);
getch();
}
Output:
How many numbers:5
Enter the numbers :9 0 2 1 7
The sorted list ... 0 1 2 7 9

14 | P a g e
Searching:
Searching is a technique which searches for the given element in the array.
Ex: Google Search Engine, Searching for a file, etc are based on this concept. Searching’s are of two types
namely:
1. Linear Search
2. Binary Search
Linear Search:
This technique searches for the element sequentially i.e., it searches for the search element starting
from the first element in the array. If the search values do not match with the first element in the array
then the search element is compared with the second element in the array. If the values still do not match
then the required element is compared with the third element in the list. This process continues, until the
required element is found or the end of the list is reached.
Ex: Searching for the file starting with the letter ‘s’, searching for files having extensions like .doc,.xls etc.
//program for linear search
#include<stdio.h>
void main()
{
int a[10],n,i,search,flag=0;
clrscr();
printf("How many numbers:");
scanf("%d",&n);
printf("\nEnter the numbers :");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the element to be searched:");
scanf("%d",&search); //reading search element
for(i=0;i<n;i++)
{
if(a[i]==search) // comparing search element to the
{ //element in the array list.
flag=1;
break; //if element is found make flag=1
}
}
if(flag==1) //if flag=1 it means element found
printf("\nElement found at position %d",i+1);
else //i+! is the element position
printf("\nElement Not Found");
getch();
}
Output:
How many numbers: 5
Enter the numbers: 2 8 4 7 1
Enter the element to be searched: 4
Element found at position 3

15 | P a g e
Output 2:
How many numbers: 5
Enter the numbers: 2 8 4 7 1
Enter the element to be searched: 6
Element Not Found
Explanation:
Initially flag=0
Elements in the array:
1 8 9 4 5
a[0] a[1] a[2] a[3] a[4]
Assume Search element as 9
First compare 9 with a[0] i.e., 1 (not equal)
Next compare 9 with a[1] i.e., 8 (not equal)
Next compare 9 with a[2] i.e., 9 (equal)
Now assign flag=1 and break the loop and check whether flag=1 or not if yes print the message “element
found”.
Assume Search element as 6
First compare 6 with a[0] i.e., 1 (not equal)
Next compare 6 with a[1] i.e., 8 (not equal)
Next compare 6 with a[2] i.e., 9 (not equal)
Next compare 6 with a[3] i.e., 4 (not equal)
Next compare 6 with a[4] i.e., 5 (not equal)
Now it reaches to the end of the list so the flag value will not change it remains 0 so it prints “element not
found”

Binary Search:
In this search, to search the element first the list of elements should be in the sorted order. The
searching is done by finding the middle element in the array. If the middle element is equal to the search
element the procedure stops. Otherwise it splits the list into 2 halves, if search element is greater than the
middle element then it search in the lower list, if the search element is less than the middle element then
it search in the upper list. This procedure repeats until the search element is found.
For Ex: Searching for a word in a dictionary comes under this concept. Suppose we want to search the
meaning for knowledge we directly move to the page containing k letter and then to the letters kn and so
on. The words will be in the sorted order in the dictionary. So we can directly move to that page that
containing the alphabet.
Ex-2: Telephone Directory, etc
//Program for Binary Search
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],flag=0,i,n,top,mid,bottom,key; clrscr();
printf("\nEnter size of the array:");
scanf("%d",&n);
printf("\nEnter elements into the array in sorted order:");
for(i=0;i<n;i++)

16 | P a g e
scanf("%d",&a[i]);
printf("\nEnter element to be searched:");
scanf("%d",&key);
top = 0;
bottom = n-1;
while(top <= bottom && flag == 0)
{
mid = (top + bottom) /2 ;
if(a[mid] == key)
flag = 1;
else if(key>a[mid])
top = mid + 1;
else
bottom = mid - 1;
}
if(flag == 1)
printf("\nSearch element %d found at position %d",key,mid+1);
else
printf("\nSearch element %d is not found.",key);
}
Output
Enter size of the array: 5
Enter elements into the array in sorted order: 10 20 30 40 50
Enter element to be searched: 40
Search element 40 found at position 4
Now search element is 10

top mid bottom Key=10


2 5 6 7 8 9 10 11 Top=0; bottom=n-1=7
0 1 2 3 4 5 6 7 Mid=top+bottom/2 = 0+7/2 = 3
A[3]=7
key>a[3] so, top=mid+1 i.e., it breaks the list into 2 now search will be in the bottom part of the list
as key > mid element.

top mid Bottom Key=10


2 5 6 7 8 9 10 11 Top=4; bottom = n-1=7
0 1 2 3 4 5 6 7 Mid=top+bottom/2=4+7/2=5
A[5]=9
key>a[5] so, top=mid+1 i.e., it breaks the list again into 2 now search will be in the bottom part of
the list as key > mid element.

top mid Bottom Key=10


2 5 6 7 8 9 10 11 Top=5; bottom=n-1=7
0 1 2 3 4 5 6 7 Mid=top+bottom/2=5+7/2=6
A[6]=10 // a[mid] is equal to key so search found

17 | P a g e
Now search element is 12

top mid bottom Key=12


2 5 6 7 8 9 10 11 Top=0;bottom=n-1=7
0 1 2 3 4 5 6 7 Mid=top+bottom/2=0+7/2=3
A[3]=7
key>a[3] so, top=mid+1 i.e., it breaks the list into 2 now search will be in the bottom part of the list
as key > mid element.

top A[mid] Bottom Key=12


2 5 6 7 8 9 10 11 Top=4;bottom=n-1=7
0 1 2 3 4 5 6 7 Mid=top+bottom/2=4+7/2=5
A[5]=9
key>a[5] so, top=mid+1 i.e., it breaks the list again into 2 now search will be in the bottom part of
the list as key > mid element.

top A[mid] bottom Key=12


2 5 6 7 8 9 10 11 Top=5;bottom=n-1=7
0 1 2 3 4 5 6 7 Mid=top+bottom/2=5+7/2=6
A[6]=10
key>a[6] so, top=mid+1 i.e., it breaks the list again into 2 now search will be in the bottom part of
the list as key > mid element.

top bottom Key=12


2 5 6 7 8 9 10 11 Top=6;bottom=n-1=7
0 1 2 3 4 5 6 7 Mid=top+bottom/2=6+7/2=6
A[6]=10
key>a[6] so, top=mid+1 i.e., it breaks the list again into 2 now search will be in the bottom part of
the list as key > mid element.

Top,bottom Key=12
2 5 6 7 8 9 10 11 Top=7;bottom=n-1=7
0 1 2 3 4 5 6 7 Mid=top+bottom/2=7+7/2=7
A[7]=11
key>a[6] so, top=mid+1 i.e., it breaks the list again into 2 now search will be in the bottom part of
the list as key > mid element.

Top,bottom Key=12
2 5 6 7 8 9 10 11 Top=8;bottom=n-1=7 as top>bottom it stops searching and
0 1 2 3 4 5 6 7 prints element not found

Two-Dimensional Array :
A 2-D array is nothing but a collection of 1-D Array. 2-D arrays are mainly used when values are to
be stored in the table form or to represent in rows and columns format. 2-D arrays are used to represent
any data in table or rows and columns format.

18 | P a g e
Declaration of 2-D Array:
Syntax: datatype arrayname[row size][col size];
int m[5][4];
Here m is an array variable which has 5 rows and 4 columns. Here 40 bytes (20 integers) gets
allocated to ‘m’.
0 1 2 3
M[0][0]
0
1
M[2][2]
2
3
4

M[4][1] M[4][3]

Initialization of 2-D Array:


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

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

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

Here the first dimension is optional but the 2nd dimension is compulsory because the compiler should know
the number of elements in each of 1-D arrays.
1 7 1
7 2 1
2 1 3
1 2 2 2 2
int a[ ][5]={1,2,2,2,2,2,1,1,1}; 2 1 1 1

Organization of 2-D array elements in memory:


They are internally stored in adjacent locations
int m[4][4];

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
100 102 104 106 108 110 112 114 116 118 120 122 124 126 128 130

19 | P a g e
//Program for reading & printing a 2-D array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],m,n,i,j;
printf("Enter the size of matrix:");
scanf("%d%d",&m,&n);
printf("\nEnter the elements into array:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nElements in the array are:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
getch();
}
Output
Enter the size of matrix:2 2
Enter the elements into array:1 2 3 4
Elements in the array are:
1 2
3 4

//addition of 2 matrices
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],i,j,m,n,p,q;
clrscr();
printf("Enter the size of matrix A:");
scanf("%d%d",&m,&n);
printf("\nEnter the elements into matrix A:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the size of matrix B:");
scanf("%d%d",&p,&q);
printf("\nEnter the elements into matrix B:");

20 | P a g e
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
if((m!=p) && (n!=q))
printf("\nMatrix Addition is not possible");
else
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\nAddition of 2 matrices are...\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",c[i][j]);
}
printf("\n");
}
}
getch();
}
Output:
Enter the size of matrix A: 3 3
Enter elements into matrix-A:
123456789
Enter the size of matrix B: 3 3
Enter elements into matrix-B:
123456789
Addition of 2 matrices are...
2 4 6
8 10 12
14 16 18

//multiplication of 2 matrices
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],k,i,j,m,n,p,q;
clrscr();
printf("Enter the size of matrix A:");

21 | P a g e
scanf("%d%d",&m,&n);
printf("\nEnter the elements into matrix A:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the size of matrix B:");
scanf("%d%d",&p,&q);
printf("\nEnter the elements into matrix B:");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
if((m!=q) && (n!=p))
printf("\nMatrix Multiplication is not possible");
else
{
for(i=0;i<m;i++)
{
c[i][j]=0;
for(j=0;j<p;j++)
{
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
printf("\nMultiplication of 2 matrices are...\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",c[i][j]);
}
printf("\n");
}
}
getch();
}
Output
Enter the size of matrix A: 3 3
Enter elements into matrix-A:
123456789
Enter the size of matrix B: 3 3
Enter elements into matrix-B:
123456789

22 | P a g e
Multiplication of 2 matrices are...
30 36 42
66 81 96
102 126 150
//transpose matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],i,j,m,n,p,q;
clrscr();
printf("Enter the size of matrix A:");
scanf("%d%d",&m,&n);
printf("\nEnter the elements into matrix A:");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nOriginal Matrix is...\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
printf("\nTranspose of matrices is...\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=a[j][i];
printf("%3d",b[i][j]);
}
printf("\n");
}
getch();
}
Output:
Enter the size of matrix A: 4 3
Enter the elements into matrix A: 1 2 3 4 5 6 7 8 9 10 11 12
Original Matrix is:
1 2 3
4 5 6
7 8 9
10 11 12

23 | P a g e
Transpose of matrices is:
1 4 7 10
2 5 8 11
3 6 9 12

Multi-Dimensional Array:
Multi-dimensional arrays are widely used in scientific computing. A 3-D array is
a combination of 2-D array.
Ex: int x[2][4][5]
It is considered as 3-D array in which there exist two 2-d arrays of size 4 rows and 5 columns.

Initialization of 3-D array:


int a[2][4][5] : {{{1,2},{1,4}},{{3,4},{4,5}}};
1 2 3 4
1 4 4 5

//reading and printing 3-d array:


#include<stdio.h>
void main()
{
int a[2][4][5],i,j,m,k,n,p;
clrscr();
printf("enter the no of planes,its rows and coloumns:");
scanf("%d%d%d",&p,&m,&n);
printf("\nenter the elements into array:"); /*reading the array*/
for(k=0;k<p;k++)
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\nEnter next value");
scanf("%d",&a[k][i][j]);
}
}
}

24 | P a g e
/* printing the data */
for(k=0;k<p;k++)
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[k][i][j]);
}
printf("\n");
}
}
getch();
}

Output:
enter the no of planes,its rows and coloumns:2 2 2
enter the elements into array:
Enter next value1
Enter next value2
Enter next value3
Enter next value4
Enter next value1
Enter next value2
Enter next value3
Enter next value4
1 2
3 4
1 2
3 4

STRINGS:
1-D character Arrays:
Like an integer array, a group of characters can be stored in a character array. These character
arrays are often called as strings. A string is an array of characters. A string is a nothing but a collection of
characters.
The string science would be stored as
S C I E N C E \0
\0 – Null indicates the end of the string.

Defining a 1-D character Array:


char st[20];
The above statement tells the compiler to reserve sufficient amount of space to store 20 characters and
specify a name st to the entire collection.

25 | P a g e
Initialization of 1-D character array:
char st[]={‘v’,’I’,’k’,’r’,’a’,’m’};
Or
char st[]=”vikram”;

Reading/printing a group of characters


#include<stdio.h>
void main()
{
char st[30];
clrscr();
printf("Enter the name:");
scanf("%s”, st);
printf("The entered name is:%s “,st)
}
Output:
Enter a name: Pawan Kalyan
The entered name is Pawan Kalyan
The %s format specifier in the scanf() keeps on reading the characters until it encounters a
whitespace character(space/tab spcae/enter key) and place a special character called as null character at
the end of the string. The %s format in scanf( ) can accept only single word. So the above output. gets( ) is
an exclusive function for reading strings. Puts( ) is a function which prints the given string.
#include<stdio.h>
void main( )
{
char na[30];
printf("Enter the name:");
gets(na);
printf("%s",na);
}
Output
Enter a name: Pawan Kalyan
Pawan Kalyan

The common operations performed on character strings are:


1. Reading & Printing Strings
2. Combining 2 strings together
3. Copying 1 string into another
4. Comparing 2 strings etc.
We can perform these operations through string functions which are defined by c and defined in <string.h>
header file
String Handling Using String Library Functions:
Some of the predefined string functions are:

26 | P a g e
1. strlen ( ) : this function is used to find out the length of the string.
Syntax: strlen(var_name);
Ex: char name=" Pawan Kalyan "
strlen(name); //it returns 12
//program for finding the string length
#include<string.h>
#include<stdio.h>
void main( )
{
char na[30];
int l;
printf("Enter the name:");
gets(name);
l=strlen(name);
printf("Length of the string is ...%d",l);
}
Output
Enter the name: Pawan Kalyan
Length of the string is…12

2. strcpy ( ) : this function is used to copy string from one into another string.
Syntax: strcpy(target_string,source_string);
Ex: strcpy(str2,str1);
//program for copying one string into the other string
#include<stdio.h>
#include<string.h>
void main( )
{
char source[30],target[30];
printf("Enter the name:");
gets(source);
strcpy(target,source);
printf("Source String is...%s\n",source);
printf("Target String is...%s\n",target);
}
Output
Enter the name: gayatri
Source String is…gayatri
Target String is…gayatri

3. strrev ( ) : this function is used to reverse the given string.


Syntax: strrev(string);
ex: strrev(str1);
//program for reversing string
#include<stdio.h>
#include<string.h>

27 | P a g e
void main( )
{
char source[30];
printf("Enter the name:");
gets(source);
strrev(source);
printf("Reverse String is...%s\n",source);
}
Output
Enter the name: gayatri
Reverse String is...irtayag

4. strcmp ( ) : this function is used to compare the given two string.


Syntax: strcmp(str1,str2);
ex: strcmp(str1,str2);
//program for comparing string
#include<stdio.h>
#include<string.h>
void main( )
{
char source[30],dest[30];
int n;
printf("Enter the source name:");
gets(source);
printf("\nEnter the destination name:");
gets(dest);
n=strcmp(source,dest); //if it is same it returns 0 otherwise -1
if(n==0)
printf("The given 2 strings are same");
else
printf("The given 2 strings are not same");
}
Output
Enter the source name: gayatri
Enter the destination name: gayatri
The given 2 strings are same
Enter the source name: gayatri
Enter the destination name: vidya
The given 2 strings are not same

5. strcat ( ) : this function is used to combine the given two string.


Syntax: strcat(str1,str2);
Ex: strcat(str1,str2);
//program for concatenating 2 strings
#include<stdio.h>
#include<string.h>

28 | P a g e
void main( )
{
char first[30],second[30],combine[30];
printf("Enter the first name:");
gets(first);
printf("\nEnter the second name:");
gets(second);
strcpy(combine,first); // first copy first name
into combine
strcat(combine,second); //now add second
name to combine
printf("First Name:%s",first);
printf("Second Name:%s",second);
printf("Combined Name:%s",combine);
}
Output
Enter the first name: gayatri
Enter the second name: vidya
Combined Name: gayatrividya

6. strlwr( ): it converts given string into lowercase


Syntax: strlwr("GVP");

7. strupr( ): it converts given string into uppercase


Syntax: strupr("gvp");

A palindrome is nothing but when a name is given if its reversed the reversed name should be
same to the given number. Ex: Liril, Malayalam
/* String Palindrome using string functions */
#include<stdio.h>
#include<string.h>
main()
{
char str[50],str1[50];
int n;
clrscr();
printf("Enter the string:");
gets(str);
strcpy(str1,str); //string copying
strrev(str1); //string reversing
n=strcmp(str1,str); //string comparison
if(n==0)
printf("\ngiven string is palindrome");
else
printf("\ngiven string is not palindrome");
getch();

29 | P a g e
}
Output:
Enter the string: liril
given string is palindrome

/* String Palindrome without using string functions */


#include<stdio.h>
#include<string.h>
main()
{
char str[50],str1[50];
int flag=0,i,l=0,j;
clrscr();
printf("Enter the string:");
gets(str);
for(i=0;str[i]!='\0';i++)
l++; /* length of the given string */

for(i=0,j=l-1;j>=0;i++,j--)
str1[j]=str[i]; /* reversing the string */

for(i=0;i<l;i++)
{
if(str1[i]==str[i]) /* str contains the given string */
continue; /*str1 contains the reverse string */
else /* comparing 2 strings */
flag=1;
}
if(flag==0)
printf("\ngiven string is palindrome");
else
printf("\ngiven string is not palindrome");
getch();
}

30 | P a g e

You might also like