Sie sind auf Seite 1von 16

Birla Institute of Technology & Science, Pilani

Second Semester 2015-2016, Computer Programming [CS F111]


Week #6
Tutorial Sheet #1 Date:___/_____/________
Name: ______________ _____________ID: ______________________ Lec Sec/Lab
Sec:______/_____

Section 1 Concept of Arrays:


One of the frequently arising problem is to store and process similar types of data. For
example: If the we want to store marks of 100 students. This can be done by creating 100
variables individually but, this process is rather tedious and impracticable. These type of
problems can be handled in C programming using arrays.
Definition: An array is a sequence of data item of homogeneous value(same type).
How do we tell the compiler that we are going to store a sequence of data of the same
type?
Well this is done by declaring the array in the following manner which declares a single
dimensional array.
data_type array_name[array_size];

Array elements
In the above declaration array_size defines the number of elements in an array. Each
element of array can be accessed by using a subscript or index of the element.
Example: Declare an array of 5 elements to store age of poeple which are type int.
int age[5];
The following are the way they would be stored in the memory.

Exercise 1: Declare an array of 100 elements to store marks of students which are type
float.
float marks[100];

Exercise 2: Declare an array of 20 characters to store name


char name[20];

Initialization of one-dimensional array:


Arrays can be initialized at declaration time in the source code as follows:
int age[5]={2,4,34,3,4};
or int age[]={2,4,34,3,4}; // In this case, the compiler determines the size of

array by

calculating the number of elements of an array.

You can use array members from age[0] to age[9]. But, what if you want to use
element age[10],age[13] or aage[-1]etc. Compiler may not show error using these elements
but, they would return garbage values.
Partial Initialization:

int age[5]={2,4};

Initializing array elements to 0


int age[5]={0};

Reading and printing array elements:


Since array stores group of elements we need to place the scanf statement within a loop.
For example if we wish to read age of 5 people then the following is how we do it.
for(i=0;i<5;i++)
scanf(%d,&age[i]);

if we wish to print age of 5 people then the following is how we do it.


for(i=0;i<5;i++)
printf(%d,age[i]);

Example : Write a C program to read N integers into an array and perform the following:
a) Find the sum of negative numbers
b) Find the sum of positive numbers
c) Find the average of all numbers
#include <stdio.h>
#define MAXSIZE 10
int main()
{
int array[MAXSIZE];
int i, num, negative_sum = 0, positive_sum = 0;
float total = 0.0, average;
printf ("Enter the value of N \n");
scanf("%d", &num);
printf("Enter %d numbers (-ve, +ve and zero) \n", num);
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array elements \n");
for (i = 0; i < num; i++)
{
printf("%+3d\n", array[i]);
}
/* Summation starts */
for (i = 0; i < num; i++)
{
if (array[i] < 0)
{
negative_sum = negative_sum + array[i];
}
else if (array[i] > 0)
{
positive_sum = positive_sum + array[i];
}
else if (array[i] == 0)
{
;
}
total = total + array[i] ;
}
average = total / num;
printf("Sum of all negative numbers = %d\n",negative_sum);
printf("Sum of all positive numbers = %d\n", positive_sum);
printf("Average of all input numbers = %f\n", average);
}

Exercise 3: Write C program to reverse the elements of array. (Example if array contents
are 1 2 3 4 5 after reversing contents of array should be 5 4 3 2 1).
#include<stdio.h>
main()
{
int a[10],temp,i,j,n;
printf("Enter the size of the array");
scanf("%d",&n);
printf("Enter the number of elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0,j=n-1;i<n/2;i++,j--)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
printf("Elements after reversing \n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}

Exercise 4: Write a C program to copy elements of an array A into another array B so


that following sequences should be followed:
1. All even elements of A from left to right are copied into C from left to right.
2. All odd elements of A from left to right are copied into C from right to left.
#include<stdio.h>
main()
{
int a[10]={1,2,3,4,5,6,7,8,9,10};
int b[10]={0},n ,i=0,lindex=0,rindex;
printf("Enter the size of array : ");
scanf("%d",&n);
printf("\n Enter the elements of array : ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
rindex=n-1;
for(i=0;i<=n-1;i++)
{
if(a[i] % 2 == 0)
b[lindex++] = a[i];
else
b[rindex--]=a[i];
}
for(i=0;i<n;i++)
printf("%d\n",b[i]);
}

Exercise 5: Assume that you are given temperatures of all 12 months in the years 2014
and 2015 which are stored in two arrays. Write a C program to identify the months
having same temperatures.
#include<stdio.h>
main()
{
int year1[]={23,24,35,40,45,36,23,22,33,36,40,22};
int year2[]={32,24,35,34,41,36,32,20,33,38,42,22};
int i=0;
printf("The following months have same temperatures\n");
for(i=0;i<12;i++)
{
if(year1[i]==year2[i])
printf("%d\n",i+1);
}

Section 2 Multidimensional Arrays:


C programming language allows programmer to create arrays of arrays known as
multidimensional arrays. For example:
int a[2][6];
Here, a is an array of two dimension, which is an example of multidimensional array.
For better understanding of multidimensional arrays, array elements of above example
can be thought of as follows:

You may be wondering how the two dimension arrays are stored in the memory in
linearly. The two dimensional array is treated as array of single dimensional array. In C
language each row is stored one after the other as shown below.
2000
a[0][0]
row 1
2004
a[0][1]
2008
a[0][2]
2012
a[0][3]
2016
a[0][4]
2020
a[0][5]
2024
a[1][0]
row2
2028
a[1][1]
2032
a[1][2]
2036
a[1][3]
2040
a[1][3]
2044
a[1][5]
2048
a[1][6]
Initialization of Multidimensional Arrays
In C, multidimensional arrays can be initialized in different number of ways.
int c[2][3]={{1,3,0}, {-1,5,9}};
OR
int c[][3]={{1,3,0}, {-1,5,9}};
OR

int c[2][3]={1,3,0,-1,5,9};

Partial initialization
int c[2][3]={{1,3}, {-1,5}};

Here the first row third column will be 0 i.e c[0][2]=0 and second row third column will
be 0 i.e c[1][2]=0
Exercise 6: Declare an array of 3X3 integers and initialize the array with the values
of your choice such that the complete second row elements must be 0.
Zero initialization
int c[3][3]={0};

Here all the 9 elements will be assigned 0;


Reading and printing array elements:
Since this array is two dimensional array we need two loop one to keep track of the rows
and the other for columns.
For example if we wish to read marks of 10 students in 5 different courses whose array
declaration is float marks[10][5];
for(i=0;i<10;i++)
for(j=0;j<10;j++)
scanf(%f,&marks[i][j]);

if we wish to print the values of the marks array shown above the following is how we
do it.
for(i=0;i<10;i++)
for(j=0;j<10;j++)
printf(%f,marks[i][j]);

Example: Write C program to find addition of two 2-dimensional arrays (Matrix)


#include<stdio.h>
int main(){
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter the First matrix->");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the Second matrix->");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
printf("\nThe First matrix is\n");
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
}
printf("\nThe Second matrix is\n");
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",b[i][j]);
}
for(i=0;i<3;i++)

for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\nThe Addition of two matrix is\n");
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
}
return 0;

Exercise 6: Write a C program for square matrix to calculate


i) Left diagonal sum
ii) Sum of upper triangle
iii) Find maximum in element in each row (and/or column).
iv) it transpose (i.e. change rows to columns and columns to rows)
i)
#include<stdio.h>
main()
{
int a[5][5],i,j,sum=0,r,c;
printf("enter a number of rows and columns for a square
matrix\n");
scanf("%d%d",&r,&c);
//check if the matix is a square matrix
if(r==c)
{
//read the elements of the matrix
printf("Enter the array elements\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
//finding the left diagonal sum
for(i=0;i<r;i++)
for(j=0;j<c;j++)
if(i+j == (r-1))
sum=sum+a[i][j];
printf("%d",sum);
}
else
printf("not a square matrix\n");
}
ii)
#include<stdio.h>
int main(){
int i,j,a[10][10],sum=0,rows,columns;
printf("\nEnter the number of Rows and columns : ");
scanf("%d%d",&rows,&columns);
if(rows == columns){
for(i=0;i<rows;i++){
for(j=0;j<columns;j++){
printf("\nEnter the Element a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<rows;i++){
for(j=0;j<columns;j++){
// Condition for Upper Triangle
if(i<j){

}
}
}
else
}

sum=sum+a[i][j];

printf("\nSum of Upper Triangle Elements:%d",sum);

printf("not a square matrix\n");


return 0;

iii)
#include<stdio.h>
int main()
{
int i,j,a[10][10],max[10],rows,columns;
printf("\nEnter the number of Rows and columns : ");
scanf("%d%d",&rows,&columns);
for(i=0;i<rows;i++){
for(j=0;j<columns;j++)
{
printf("\nEnter the Element a[%d][%d]:",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i<rows;i++)
{
max[i]=a[i][0];
for(j=0;j<columns;j++)
{
if(a[i][j] > max[i])
max[i]=a[i][j];

}
}
for(i=0;i<rows;i++)
printf("Max in row %d is %d\n",i,max[i]);
return 0;

iv)
#include <stdio.h>
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
printf("Enter the number of rows and columns of matrix ");
scanf("%d%d",&m,&n);
if(m == n){
printf("Enter the elements of matrix \n");
for( c = 0 ; c < m ; c++ )
for( d = 0 ; d < n ; d++ )
scanf("%d",&matrix[c][d]);
for( c = 0 ; c < m ; c++ )
for( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];
printf("Transpose of entered matrix :-\n");
for( c = 0 ; c < n ; c++ ) {
for( d = 0 ; d < m ; d++)
printf("%d\t",transpose[c][d]);
printf("\n");
}

}
else
printf("not a square matrix\n");
return 0;
}

Exercise 7: Write a C program to store students marks in 5 courses and provide a menu
to user where he/she will enter 1,2 or 3 and based on the input the corresponding values
have to be displayed:
1. Find the highest marks for each students.
2. Find the highest mark in each course.
3. Find the average marks in each course.
#include<stdio.h>
main()
{
int a[5][5];
int rows,cols,highest=0,max=0,sum=0;
float avg=0;
printf("enter the number of students and courses");
scanf("%d%d",&rows,&cols);
int i=0,j=0;
//read the marks for each student in different courses
for(i=0;i<rows;i++)
{
printf("enter marks for %d courses for the
student",cols);
for(j=0;j<cols;j++)
scanf("%d",&a[i][j]);
}
//Find the highest marks for each students.
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
if(a[i][j] > max)
max=a[i][j];
}
printf("maximum marks for %d student is %d\n",i,max);
max=0;
}
//Find the highest marks for each course.
for(i=0;i<cols;i++)
{
for(j=0;j<rows;j++)
{
sum+=a[j][i];
if(a[j][i] > highest)
highest=a[j][i];
}
avg=(float)sum/rows;
printf("maximum marks for %d course is %d\n",i,highest);
printf("Average marks for %d course is %f\n",i,avg);
highest=0;
sum=0;avg=0;
}
}

Birla Institute of Technology & Science, Pilani


Second Semester 2015-2016, Computer Programming [CS F111]
Week #6
Tutorial Sheet #2 Date:___/_____/________
Name: ______________ _____________ID: ______________________ Lec Sec/Lab
Sec:______/_____

Section 1 Linear Search:


Linear search is a very simple search algorithm. In this type of search, a sequential
search is made over all items stored in the array one by one. Every items is checked
and if a match founds then that particular item is returned otherwise search
continues till the end of the data collection. The following is the algorithm and
program for linear search.
#include<stdio.h>
Step 1: Set i to 1
int main(){
Step 2: if i > n then go to step
int a[10],i,n,m,c=0;
7
Step 3: if A[i] = x then go to
printf("Enter the size of an
step 6
array: ");
Step 4: Set i to i + 1
scanf("%d",&n);
Step 5: Go to Step 2
Step 6: Print Element x Found
at index i and go to step 8
Step 7: Print element not
found
Step 8: Exit

printf("Enter the elements of the


array: ");
for(i=0;i<=n-1;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to be
search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++){
if(a[i]==m){
c=1;
break;
}
}
if(c==0)
printf("The number is not in
the list");
else
printf("The number is
found");
return 0;
}

Example 1: If the elements of an array are {20, 34, 12, 4, 5, 6} how many
comparisons are required to find the element 4?
We will have to compare 12 with 20, 34, 12, 4 hence 4 comparisons will be required
to find the element 4.
Exercise 1: If the elements of an array are {20, 4, 12, 4, 5, 6} how many
comparisons are required to find the element 4?
We will have to compare 12 with 20, 4, hence 2 comparisons will be
required to find the element 4.

Example 2: Having understood the linear search find all the occurrences of key in
the array.
#include <stdio.h>
int main()
{
int size = 10, no_of_occurences = 0, i, key;
int A[size];
int O[size];
//Initialize array
for(i = 0; i < size; i++){
scanf("%d",&A[i]);
}
//read the key
scanf("%d", &key);
//now do linear search
for(i = 0; i < size; i++){
if(key == A[i]){
O[no_of_occurences] = i;
no_of_occurences++;
}
}
//OUTPUT THE RESULT
for(i = 0; i < no_of_occurences; i++){
printf("%d ",O[i]);
}
return 0;
}
Exercise 2:
b) Find the index of the last occurrence of key in an array.
#include <stdio.h>
int main()
{
int size = 10, last_occurence = 0, i, key;
int A[size];
//Initialize array
for(i = 0; i < size; i++){
scanf("%d",&A[i]);
}
//read the key
scanf("%d", &key);
//now do linear search
for(i = size-1; i >= 0; i--)
{
if(key == A[i]){
last_occurence = i;
break;
}
}
//OUTPUT THE RESULT
printf("%d \n",last_occurence);
return 0;
}

c) Find the index of last occurrence of key in a 2-D array.


#include <stdio.h>
int main()
{
int r = 4, c= 3, last_occurence = 0,lr,lc, i, j, key;
int A[r][c];
//Initialize array
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
scanf("%d",&A[i][j]);
}
}
//read the key
scanf("%d", &key);
//now do linear search
for(i = r-1; i >= 0; i--)
{
for(j = c-1; j >= 0; j--){
if(key == A[i][j]){
last_occurence = i;
lr = i; lc = j;
break;
}
}
if(last_occurence)
break;
}
//OUTPUT THE RESULT
printf("Row = %d Column = %d\n",lr, lc);
return 0;
}

d) Find all the occurrences of key in a 2-D array.


#include <stdio.h>
int main()
{
int r = 4, c= 3,i, j, key;
int A[r][c];
int O[r][c]={0};
//Initialize array
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
scanf("%d",&A[i][j]);
}
}
//read the key
scanf("%d", &key);
//now do linear search
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
if(key == A[i][j]){
O[i][j] = 1;
}
}
}
//OUTPUT THE RESULT
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
if(O[i][j]){
printf("Row = %d Column = %d\n",i, j);
}
}
}
return 0;
}

Section 2 Binary Search:


Since the linear search take a lot of comparison a better approach for searching is
by using a binary search. Binary Search is applied on the sorted array or list.
In binary search, we first compare the value with the elements in the middle
position of the array. If the value is matched, then we return the value. If the value
is less than the middle element, then it must lie in the lower half of the array and if
it's greater than the element then it must lie in the upper half of the array. We
repeat this procedure on the lower (or upper) half of the array. Binary Search is
useful when there are large numbers of elements in an array.
Example 3:To search an element 13 from the sorted array or list how many
comparisons are required?
2

13

Observe that the array is sorted and has odd number of elements.
First comparison will be 13==7
Second comparison will be 9== 13
Third comparison will be 13== 13
Hence 3 comparisons are needed.
Exercise 4: How many comparisons will be required to find 6 and 103 in this
array[]= {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}?
Find 6 in {-1, 5, 6, 18, 19,
Step 1 (middle element is
Step 2 (middle element is
Step 3 (middle element is

25, 46, 78, 102, 114}.


19 > 6):
-1 5 6 18 19 25 46 78 102 114
5 < 6):
-1 5 6 18 19 25 46 78 102 114
6 == 6):
-1 5 6 18 19 25 46 78 102 114

Hence 3 comparisons are needed.


Find 103 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}.
Step 1 (middle element is 19 < 103): -1 5 6 18 19 25 46 78 102 114
Step 2 (middle element is 78 < 103): -1 5 6 18 19 25 46 78 102 114
Step 3 (middle element is 102 < 103): -1 5 6 18 19 25 46 78 102 114
Step 4 (middle element is 114 > 103): -1 5 6 18 19 25 46 78 102 114
Step 5 (searched value is absent):
-1 5 6 18 19 25 46 78 102 114
Hence 5 comparisons are needed.

Exercise 5:Binary search is covered in video lecture on 1D array and some


particular row of 2D array. Modify binary search to:
a) First find the row in which the element can be there (using linear search on the
first column); and then find the element in that row (using binary search). Assume
here that matrix is strictly sorted, i.e. elements are entered in increasing order row
wise such that the first element of each row is greater than the last element of the
previous row.

Section 3: Sorting
selection sort
The selection sort algorithm sorts an array by repeatedly finding the minimum
element (considering ascending order) from unsorted part and putting it at the
beginning. The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.

2) Remaining subarray which is unsorted.


In every iteration of selection sort, the minimum element (considering ascending
order) from the unsorted subarray is picked and moved to the sorted subarray.
Following example explains the above steps:
arr[] = 64 25 12 22 11
// Find the minimum element in arr[0...4] and place it at beginning
11 25 12 22 64
// Find the minimum element in arr[1...4] and
// place it at beginning of arr[1...4]
11 12 25 22 64
// Find the minimum element in arr[2...4] and
// place it at beginning of arr[2...4]
11 12 22 25 64
// Find the minimum element in arr[3...4] and
// place it at beginning of arr[3...4]
11 12 22 25 64
Example: Consider the following example of selection sort being carried out on a
sample set of data:
9 2 5 7 4 8 what will be the result after 2 passes/iterations?
Solution:
9 2 5 7 4 8 on pass 1 look for smallest in 1st to 6th
swap 2nd with first giving
2 9 5 7 4 8 on pass 2 look for smallest in 2nd to 6th
swap 5th with second giving
Exercise 6: what will be the result after 4 passes/iterations?
2 4 5 7 9 8 on pass 3 look for smallest in 3rd to 6th
swap 3rd with third giving
2 4 5 7 9 8 on pass 4 look for smallest in 4th to 6th
swap 4th with fourth giving
Example : Write a C program to perform selection sort on an array in ascending
order
#include<stdio.h>
int main(){
int s,i,j,temp,a[20];
printf("Enter total elements: ");
scanf("%d",&s);
printf("Enter %d elements: ",s);
for(i=0;i<s;i++)
scanf("%d",&a[i]);
for(i=0;i<s;i++){
for(j=i+1;j<s;j++){
if(a[i]>a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("After sorting is: ");
for(i=0;i<s;i++)
printf(" %d",a[i]);
return 0;
}

Insertion sort
In Insertion sort , sorting takes place by inserting a particular element at the
appropriate position, thats why the name- insertion sorting. In the First iteration,
second element A[1] is compared with the first element A[0]. In the second iteration
third element is compared with first and second element. In general, in every
iteration an element is compared with all the elements before it. While comparing if
it is found that the element can be inserted at a suitable position, then space is
created for it by shifting the other elements one position up and inserts the desired
element at the suitable position. This procedure is repeated for all the elements in
the list.
For instance, Take card players. They arrange the cards in a sequential order.
1:
2:
3:
4:
5:

23
23
23
23
15

| 78 45 60 15
78 | 45 60 15
45 78 | 60 15
45 60 78 | 15
23 45 60 78 |

/*Sorting Elements of an array in ascending order using insertion sort


algorithm*/
#include<stdio.h>
int main()
{
int data[100],n,temp,i,j;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
for(i=1;i<n;i++)
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to
temp>data[j] in above line.*/
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}
Example: Suppose you have the following the elements in the array
21,10,15,88,95,5 what will be the result after 2 passes/iterations?
First iteration 21,10,15,88,95,5 compare 21 with 10, 10< 21 hence 10 is inserted in
first and 21 in second position
Second iteration 10,?,21,88,95,5 compare 15 with 21, 15< 21 hence 21 is inserted
in third and then compare 15 with 10, 15>10 hence 15 will be inserted into second
position.

Exercise 7: what will be the result after 4 passes/iterations?


10,15,21,88,95,5
Exercise 8: Modify insertion sort/selection sort (covered in the video

lectures) to sort each column of the matrix.


#include <stdio.h>
int main()
{
int r = 4, c= 3,i, j, c1, temp;
int A[r][c];

//Initialize array
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
scanf("%d",&A[i][j]);
}
}
//insertion sort of the columns
for(c1 = 0; c1 < c; c1++){
for(i = 1; i < r; i++)
{
j = i;
while(j > 0 && A[j-1][c1] > A[j][c1]){
temp = A[j][c1];
A[j][c1] = A[j-1][c1];
A[j-1][c1] = temp;
j--;
}
}
}
//output the result
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++){
printf("%d ",A[i][j]);
}
printf("\n");
}
return 0;
}

Das könnte Ihnen auch gefallen