Module 3psp
Module 3psp
MODULE 3
CHAPTER 1: ARRAYS
Now suppose we have to store values into these variables then 50 scanf statements or initializing 50
values has to be done as shown:
scanf(“%d”, &marks_1);
scanf(“%d”, &marks_2);
scanf(“%d”, &marks_3);
………………..scanf(“%d”, &marks_50);
OR
marks_1= 25;
marks_2=23;
marks_3=20;
………….. so on marks_50=21;
This style of programming is fine for a small set of values. But if we have to store 1000 or 10000
values declaring so many variables is a cumbersome process. Alternative solution is Arrays!
2. DEFINITION OF ARRAYS
I. One-Dimensional Arrays: A list of items can be given one variable name using
only one subscript and such a variable is called a single subscripted variable or one
dimensional array.
a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[size]={list of values};
Examples: int marks[4]={ 95,35, 67, 87};
float temperature[5]={29.5, 30.7, 35.6, 45.7, 19.5};
b) Initialization without size: We needn’t have to specify the size of array provided
we are initializing the values in beginning itself.
Syntax: data_type array_name[ ]={list of values};
Examples: int marks[ ]={ 95,35, 67, 87};
float temperature[ ]={29.5, 30.7, 35.6, 45.7, 19.5};
c) Partial initialization: If we not specify the all the elements in the array, the
unspecified elements will be initialized to zero.
Module 3 C Programming for Problem Solving
d) Initializing all the elements zero: If we want to store zero to all the elements in
the array we can do.
Examples: int marks[4]={0};
float temperature[5]={0};
Accessing the array elements: Accessing the array element is done using a loop
statement in combination with printf statements or any other processing statements.
Example of accessing the array elements and calculating total marks is given below:
Example: void main( )
{
int total=0, marks[4]={35,44,55,67};
for(i=0; i<4; i++)
total=total+marks[i]; /* calculating total marks*/
printf(“Total marks=%d”,total);
}
Output: Total marks=201
Module 3 C Programming for Problem Solving
This diagram clearly illustrates how each individual element of array num[ ] is passed to
function square through parameter no.
3 4 8 9 10
0 1 2 3 4 num[3]=9 no
num[1]=4 copied no
num[0]=3 copied to no
num[2]=8 no
Next program illustrates how to pass an entire array to a function average( ) and
calculate average marks. First sum of all the elements of array marks
Module 3 C Programming for Problem Solving
Output:
average=71.000000
In the above example each value of array marks[ ] is copied to array scores[ ] as shown
below:
marks[0]=35 copied to scores[0]
II. Two-Dimensional Arrays: A list of items can be given one variable name using
two subscripts and such a variable is called a single subscripted variable or one
dimensional array.
Module 3 C Programming for Problem Solving
1 2 3 4 29.5 30.5
marks city_temp
35.6 45.7
5 6 7 8
Module 3 C Programming for Problem Solving
012 1234
a b
345 5678
67 8 9 10 11 12
III. Multi Dimensional Arrays: Multidimensional arrays can have three, four or
more dimensions.
A three-dimension array is an array of two dimensional arrays. It has row, column
and depth associated with it.
Declaring multidimensional arrays
int table[3][5][4];
Module 3 C Programming for Problem Solving
A[3][4][2]={
{
{ 1,2},
4 rows &
{3,4},
{5,6}, 2 columns
{7,8},
},
{ 3 depth
{ 8,9},
{10,11},
{12,13},
{14,15},
},
{
{ 8,9},
{10,11},
{12,13},
{14,15},
}
}
void main( )
{
int i,j,n,temp,a[100];
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
for(j=0;j<(n-i)-1;j++)
{
if( a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
}
Selection Sort
Selection sort will start by comparing the first element with other elements and finds
minimum element and swaps, then it starts comparing by taking second element with
other elements and so on.
#include<stdio.h>
Module 3 C Programming for Problem Solving
void main( )
{
int a[100],i,j,n,temp,pos;
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if( a[pos]>a[j])
Pos=j;
}
if(pos !=i )
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
SEARCHING: It is the process of finding the location of the specified element in a list.
The specified element is often called the search key.
If it is found search is successful, otherwise it is unsuccessful.
Ex: Binary Search, Linear Search, Sequential Search.
Module 3 C Programming for Problem Solving
Linear Search
Linear search is a very basic and simple search algorithm. In Linear search, we search
an element or value in a given array by traversing the array from the starting, till the
desired element or value is found.
#include<stdio.h>
#include<stdlib.h>
void main( )
{
int n, a[100], i, key,loc;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key == a[i]
{
loc=i+1;
break;
}
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc);
else
printf("The search is unsuccessful\n");
}
Binary Search
Binary search works only on a sorted set of elements. To use binary search on a
collection, the collection must first be sorted. The array is divided into two parts,
Module 3 C Programming for Problem Solving
#include<stdio.h>
#include<stdlib.h>
void main( )
{
int n, a[100], i, key, loc, high, low, mid;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
loc = mid+1;
break;
}
else
{
if(ele<a[mid])
high=mid-1;
else
low=mid+1;
}
}
Module 3 C Programming for Problem Solving
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc);
else
printf("The search is unsuccessful\n");
}
MODULE 3
R A J E S H \0 Delimiter ‘\0’
indicates end of
0 1 2 3 4 5 6 string
String literals are also known as string constants, is a sequence of characters enclosed
by double quotation marks is called string literals. A string literal is a constant its value
cannot be changed. Some examples are:
Examples: “New Delhi”, “I Love India” etc.
String variables are nothing but character array. Following syntax and examples
illustrates declaring string variables.
Example: char array_name[ ]= “raj”
Module 3 C Programming for Problem Solving
‘A’ 25
But this initialization can be done using a loop and assigning individual characters of
name1 to name2 as shown below:
void main( )
{
int char name1[ ]= “hello”;
int char name2[5];
for (int i=0; i<4;i++)
{
name2[i] =name1[i];
}
name2[i]= ‘\0’;
}
scanf(“%s”, name);
say input is
N E W D E L H I
Only part of a string (NEW) is read and second half (DELHI) is ignored.
N E W
Edit set Conversion code %[ ]: In addition to %s we can also use edit set conversion
code %[ ], which specifies the type of characters that can be accepted by scanf ( )
function.
Module 3 C Programming for Problem Solving
For Example say we have to accept only 0-9 digits in a string then edit set code can be
used as follows:
char name[20];
scanf(“%[0123456789]”, name)
NOTE: Suppose we want to skip particular set of characters in a string, then we have to
use:
^ symbol in edit set conversion code. Following example illustrates same:
Example 1:
char name[20];
scanf(“%[^A-Z]”, name)
C library supports a large number of string handling functions that can be used to
carry out many of the string manipulations and are stored in header file “string.h”.
Following are the most commonly used string handling functions.
1. strcpy( ) copies one string over another
2. strlen( ) finds the length of a string
Module 3 C Programming for Problem Solving
name R A V I D A V I S \0
0 1 2 3 4 5 6 7 8 9 10 11 12 13
Strcpy does not check to see whether there is room for the resulting string at the
specified location. If there is no room, it copies characters on top of whatever variables
follow in memory. This may destroy the contents of other variables.
Module 3 C Programming for Problem Solving
2. strlen():the string length function can be used to find the length of the string in
bytes. It takes the form
length=strlen(str);
The parameter to strlen, str is a string. The return value length is an integer
representing current length of str in bytes excluding the null character.
Ex: str=”CBIT”
lenth=strlen(str); //4
str=’\0’
length=strlen(str); //0
3. strcmp( ): A strcmp() is used to compare two strings. It takes the two strings as
a parameter and returns an integer value based on the relationship between two
strings.
General form of call to strcmp()
result=strcmp(first,second);
result>0 if first> second
result=0 if first==second
result<0 if first<second
4. strcat( ): often it is useful to concatenate or join two strings together. The strcat
function is used to join two strings together. The resulting string has only one null
character at the end.
General form of a call to strcat( )
strcat(first, second);
Module 3 C Programming for Problem Solving
After the call, first contains all the characters from first, followed by the ones from
second up to and including the first null character in second.
Note: strcat stops copying when it finds a null character in the second string. If it
doesn’t find a null character, strcat continues copying bytes from memory until it finds
null character. The programmer must check to make sure that the resulting string fits in
the variable.
6. strncpy( ): The strncpy function allows us to extract a substring from one string
and copy it to another location.
General form of call to strncpy
Module 3 C Programming for Problem Solving
Array of strings: Array of string is an array of one dimensional character array, which
consists of strings as its individual elements.
Declaration of array of strings: Char name[size1][size2];
Ex:
char days[7][10]={“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday”};
PROGRAMS
1. WACP to read N integers into an array A and to
i. Find the sum of odd numbers.
ii. Find the sum of even numbers.
iii. Find the average of all numbers.
Output the results compared with appropriate headings.
#include<stdio.h>
void main( )
{
int oddsum=0, evensum=0, i ,N, A[20];
float avg;
printf(“enter the size of an array\n”);
scanf(“%d”,&N)
printf(“Enter the array elements\n”);
for(i=0;i<N;i++)
Module 3 C Programming for Problem Solving
{
scanf(“%d”, &A[i]); /* reading array values*/
}
for(i=0;i<N;i++)
{
if(A[i]%2==0);
{
evensum=evensum+A[i]; /* compute even sum */
}
else
{
oddsum=oddsum+A[i]; /* compute odd sum */
}
}
avg=(evensum+oddsum)/N;
printf(“even sum is = %d\n”, evensum);
printf(“odd sum is = %d\n”, oddsum);
printf(“Average of all is = %f\n”, avg);
}
void main()
{
int a[10][10],i,j,m,n;
printf(“enter the size1 and size2 of 2 dimensional array\n”);
scanf(“%d”,&m,&n)
printf(“enter the elements of an array\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf(“the elements of 2 dimensional array are\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
printf(“%d”,a[i][j]);
printf(“\n”);
}
}
#include<stdio.h>
void main()
{
int m,n,a[5][5],i,j,large;
printf("enter the size1 and size2 of 2D array\n");
scanf("%d%d",&m,&n);
printf("enter the elements of 2d array\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d"&a[i][j]);
large=a[0][0];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
if(a[i][j]>large)
large=a[i][j];
}
printf("large=%d",large);
}
gets(str1);
printf("enter the string2\n");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
i++;
j++;
}
str1[i]='\0' ;
printf("concatanation of string is %s",str1);
}
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[100],s2[100];
int i;
printf("\nEnter the string1 :");
gets(s1);
i=0;
while(s1[i]!='\0')
{
S2[i]=s1[i];
i++;
}
s2[i]='\0';
printf("\nString2 value is %s ",s2);
}