120 likes | 232 Views
Today’s Agenda. Programming Exercise. Histogram. int main() { int freq[20],marks[50]; int i,j,n,m; n = 20; m = 10;//no. of students for(i=0;i<n;i++) //invariant freq[0..i-1] = 0 freq[i] = 0; //pre-condn: each 0>= marks[i]<=20 for(i=0;i<m;i++) scanf("%d<br>",&marks[i]);
E N D
Today’s Agenda Programming Exercise
int main() { int freq[20],marks[50]; int i,j,n,m; n = 20; m = 10;//no. of students for(i=0;i<n;i++) //invariant freq[0..i-1] = 0 freq[i] = 0; //pre-condn: each 0>= marks[i]<=20 for(i=0;i<m;i++) scanf("%d\n",&marks[i]); i=0; while(i<m) //pre-condn: freq[i] = 0; { freq[marks[i]]++; // loop invariant m <= freq[marks[i]] >= 0 i++; } printf("frequency distribution\n"); for(i=0;i<n;i++) printf("%d\n",freq[i]); }
int removeDuplicate(int a[],int size) { int i,j,flag=0,k,count,c=0; for(i=1;i<size;i++)// loop invariance is all elements between a[0..i-1] should be unique or duplicates should be less than 3 { if(a[i] == a[i-1]) { if(!flag) { j = i; flag = 1; printf("j = %d and flag = %d\n",j,flag); } } else if(flag && c > 3)// checking if the # of duplicates > 3 { printf("i=%d\n",i); count = i-j; printf("count = %d\n",count); while(count>0)//loop invariant here is 'count' number of duplicates are remaining between i to j { for(k=j;k<size-1;k++) a[k] = a[k+1]; size--; count--; } flag = 0; } c++;//increamenting the count of duplicates } return size; }
SetDef.h(Data Definitions File) #define MAX 20 typedef int set[MAX]; typedef int size; typedef enum{TRUE,FALSE}boolean;
SetOps.h #include"SetDef.h" extern void readSet(set S,size n); extern boolean isMember(set S,int x,size n); extern size setUnion(set s1,set s2,set s3,size n1,size n2);
main.c #include<stdio.h> #include"SetOps.h" int main() { set s1 ;//= {1,3,5,7,9}; set s2 ;//= {2,3,5}; set s3; int i; boolean flag; size n1,n2,n3; n1 = 5; n2 = 3; int x = 7; readSet(s1,n1); readSet(s2,n2); flag = isMember(s1,x,n1); if(flag == TRUE) printf("%d is member of s1\n",x); else printf("%d is not member of s1\n",x); n3 = setUnion(s1,s2,s3,n1,n2); for(i=0;i<n3;i++) printf("%d ",s3[i]); printf("\n"); }
SetOps.c #include"SetDef.h" #include<stdio.h> void readSet(set S,size n) { int i; for(i=0;i<n;i++) scanf("%d ",&S[i]); }
boolean isMember(set S,int x,size n) { int i; for(i=0;i<n;i++) { if(S[i] == x) return TRUE; else if(S[i] > x) return FALSE; } return FALSE; }
size setUnion(set s1,set s2,set s3,size n1,size n2) { int i,j,k,l; k=0;i=0;j=0; while((i<n1)&&(j<n2)) { if(s1[i]==s2[j]) { s3[k] = s1[i]; i++; j++; k++; } else if(s1[i]<s2[j]) { s3[k] = s1[i]; k++; i++; } else { s3[k] = s2[j]; k++; j++; } } if(i < n1) for(l=i;l<n1;l++) { s3[k] = s1[l]; k++; } else if(j<n2) for(l=j;l<n2;l++) { s3[k] = s2[l]; k++; } return k; }