Professional Documents
Culture Documents
TA ZC142 Computer Programming Date: 01/02/2013
TA ZC142 Computer Programming Date: 01/02/2013
Last Lecture
Search Techniques
Linear Search Binary Search
Todays Agenda
Sorting Techniques Insert an element into a Sorted Array Remove an element from a Sorted Array Enumerated data types
Sorting Algorithm
int main() { int a[10],t,i,j,n=5; for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=1;i<n;i++) { for(j=0;j<n-i;j++) { 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("%d\n",a[i]); }
BUBBLE SORT
int main() INSERT INTO { SORTED ARRAY int a[10],n=5,i,j,x; for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter number to be inserted\n"); scanf("%d",&x); for(i=0;i<n;i++) if(a[i] >= x) break; for(j=n;j>=i+1;j--) a[j] = a[j-1]; a[j] = x; n++; for(i=0;i<n;i++) printf("%d\t",a[i]); }
int main() DELETE AN ELEMENT { FROM AN ARRAY int a[10],n=5,i,j,x; for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter number to be deleted\n"); scanf("%d",&x); for(i=0;i<n;i++) { if(a[i] == x) break; } for(j=i;j<n-1;j++) a[j] = a[j+1]; n--; for(i=0;i<n;i++) printf("%d\t",a[i]);
#include<stdio.h> #define MAX 10 main(){ int a[MAX],i,j,min,p,n; printf("enter size of array\n"); scanf("%d\n",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n-1;i++){ min = a[i]; p = i; for(j=i+1;j<n;j++){ if(a[j]<min){ min = a[j]; p = j; } } a[p] = a[i]; a[i] = min; } printf("sorted array is as follows \n"); for(i=0;i<n;i++) printf("%d\n",a[i]);
Selection Sort
STRUCTURES
Derived data type
Structures
Its a constructed data type used for packing data of different types
Variables with different data types are grouped under a single name for convenient handling.
Examples
Date : day, month, year Book : author, title, price, year City : name, state, country, population Customer: name, address,city,telephone Student : name, idno,hostel address, year of admission, cgpa etc
strcpy(b1.author,Hanly);
scanf(%s %s %d %f %d, b1.title,b1.author,&b1.pages,&b1.price,&b1.year); b2.price = 250.50; b2.pages = 405; b3.year = 2010;
Structure Initialization
} s1 = {220,"abc",79.5},s3,s4;
s3 = s1; s2 == s1 s2 != s1
Valid assignment
invalid
avg = (s1.marks + s2.marks + s3.marks)/3; if(s1.marks > avg) printf("%s is above avg\n",s1.name); else if(s1.marks < avg) printf("%s is below avg\n",s1.name); else printf("%s is at avg\n",s1.name);
Union
Union
{
int idno; char name[20]; float marks; } stud;
Valid statements
Printf(d1 is a half day); Printf(%d %d,d1,d2); Note: compiler automatically assigns integer digits beginning with 0 to all enumeration constants.
int main(){ int week_hr=0,hrs; int a[MAX]; day_t today=friday,tom; if(today == saturday) tom = sunday; else tom = (day_t)today+1; printf("%d %d\n",today,tom); return 0; }
Any Doubts ?