programming a

0 downloads 0 Views 3MB Size Report
'Borland C++ 5.02'. I wish to acknowledge my ..... getch(); // to hold the value printed on screen till any character is given. } Here we are using 'while'-loop instead ...
PROGRAMMING ANALYSIS IN C

PROGRAMMING ANALYSIS IN C

Dedicated To,

My Late Grandfather Mitra Man Palikhe and also to School Of Engineering (SOE)-POKHARA UNIVERSITY & PALIKHE FAMILY

2069 Asoj 16/2012 October 2 ‘TUE’

Devendra Man Palikhe ([email protected]) You can get soft copy of this book @ www.scribd.com/dpalikhe

PREFACE This book entitled “PROGRAMMING ANALYSIS IN C” on C-Programming is the first of its kind being published and written by student of SCHOOL OF ENGINEERING (SOE), POKHARA UNIVERSITY. It mainly presents the programs and their solutions regarding C-Programming during first semester in Engineering. This book is meant to help the reader learn, understand, familiarize, and analyze how to program in C. This book is for the purpose of building up the creative ideas regarding C-Programming in mind of learners instead of the definitions and it includes all the difficulties that the learners encounter during their voyage in C-Programming. This book is mainly meant for the difficult programs that learners come across their journey in C-Programming and it includes all those questions which have appeared in previous examinations of POKHARA UNIVERSITY that are a hard nut to crack for the students but not merely all the questions. Most of the tough solution of this book is based on analyzing problem through possible illustrative ways, analyzing the problem for coding it into programs rather than on plain statements of rules. For the majority part, the programs are entire, real programs, rather than solitary fragments. So this book is not an opening programming manual; it assumes some experience and knowledge with programming concepts like variables, assignments, statements, loops, logics, and functions. The small programs, at last in projects that are just to enhance the creativity of the learners, are self understood as they are written in very simple statements and in sequential manner with outputs. All programs of this book are complied in ‘Borland C++ 5.02’. I wish to acknowledge my greatest indebtness to my teacher Yagyanath Rimal and my brothers Nitesh Palikhe and Nischal Palikhe for their constructive suggestions, encouragement and constant support during publication of this book. I would also like to thank all my colleagues. All the thoughtful criticisms and

critical suggestions of my friends, colleagues, readers and well-wishers for improvement of this book are heartily welcome and will be highly appreciated.

ACKNOWLEDGEMENT My sincere gratitude goes to my colleagues of school of engineering whose constant support and encouragement has always been my source of inspiration.

Devendra Man Palikhe 2௡ௗ Semester, BCE School Of Engineering POKHARA UNIVERSITY

You can get soft copy of this book @www.scribd.com/dpalikhe

CONTENTS SOME BEGINNING PROGRAMS Decision making Loop A program to convert degree Celsius to Fahrenheit A program to find positive or negative A program to find numbers between 0 to 100 divisible by 3 and not by 5 Factorial` Leap year H.C.F. by division method Reference-interchange two values Flowchart of Greatest among four numbers Greatest among three numbers Some types of numbers Armstrong numbers Even and odd numbers Prime numbers

FIBONACCI SERIES 1,

1,

2,

3,

5,

8,

13,

21 …………….……….

0,

1,

1,

2,

3,

5,

8,

13,

DIGITS OF A NUMBER Digits taking from a number

PALINDROME Palindrome for number An analysis of returning back number from its digits Palindrome for string

21

………………

Using reversing string function A char[] is declared where each time a new last character from string is taken one by one as array and then check is done to original string Palindrome for string containing even or odd quantity of characters Palindrome for string using for-loop

ELECRTICITY AUTHORITY

ARRAY 2d PU2008FALL 2b) finding an element of 2D-array Finding greatest and smallest number among ‘n’ numbers (using array)

PATTERNS OF CHARACTERS AND NUMBERS ‘Scanf’ function for numbers Patterns of characters and numbers using ‘printf’ function Basic principle of printing patterns Some more patterns Floyd’s triangle Patterns of ‘*’ Some more difficult patterns Pyramid of triangle Reverse pyramid of triangle Pascal’s triangle PU2002 FALL 5 WAP that takes angle in degrees and give out value of sine for that angle without using ‘sin ()’ function of math library Conversion Decimal to binary Binary to decimal Exclusive use of ‘switch-case’ and ‘goto’ statements 2005PU A program that takes a sum of money and converts it into smaller units, where user can choose his starting unit. The conversion is in such a way that the first starting units takes maximum possible conversion then the left sum is supplied to conjugate term following it, this process continues till the end

SORTING Selection sorting Bubble sorting Third sorting process Analysis of the solution of third sorting A special analysis in sorting-third sorting PU2011FALL 5b) Sort ‘n’ numbers by function (special) Description A SPECIAL ANALYSIS Now we are adding a new feature to above program Examples of sorting of numbers and strings in selection and bubble sorting Median and standard deviation

MATRIX ARRAY Case-1: Finding smallest and greatest of a matrix Case-2: Sum of diagonal elements of square 3*3 matrix 1. sum of diagonal from right top to left bottom 2. sum of diagonal from left top to right bottom Case-3: Finding a matrix element in a matrix Case-4: sum of all elements in a matrix Case-5: transpose of a matrix Matrix Multiplication Matrices multiplication of (3*3) and (3*3) More generalization of matrices multiplication

TASK A simple program that takes students marks in various subjects, name and roll numbers to print out ranks, roll numbers and marks (both % and marks) in Descending order. Solution of the task

RECURSIVE FUNCTION Factorial by function Factorial by recursive Fibonacci series by recursive

1

1

2

3

5

8

13

21

……………….

3

5

8

13

21

Fibonacci series by recursive 0

1

1

2

To calculate power by recursive Calculate sum of digits by recursive Armstrong using function Armstrong using recursive

WITHOUT FUNCTION To check case without using any function Calculate power without function To reverse a sentence without any function Concatenate two strings without function

A DETAIL OF STRINGS Finding a sequence of words Finding a sequence of words any Finding a sequence of words (working) Finding a word in a sentence Finding a word in a sentence (working) Finding a word in a sentence (input from user)

OPERATORS Table Post/pre increment/decrement operators For-block’s execution flow ASSIGNMENT OPERATORS

OUTPUTS Hints to PU 2008 FALL 3a)

3b

PU 2006 SPRING 2 a)

2 c)

2 b)

……………….

PU 2009 SPRING 2 b)

important

PU 2011 FALL

3 a)

3 b)

PU 2009 FALL

3 a)

3 b)

3 a) very important

PU 2007 FALL 2 a) 2 b) PU 2012 FALL 2b i) very important PU 2011 SPRING Ternary operator’s nested use PU2006FALL 3) Print out combinations of 1, 2, 3 using for-loop PUFALL2003 2 b) Read temperature of a month of 10 cities and print out average of ten cities using array and for-loop Second way of solving

POINTERS Pointer declaration in arrays Program demonstrating pointer variable’s resembling with special array i.e. character array (string) Using ‘void’ type pointer as required Demonstrating the 2d pointers in 2d array Call by address/ pass by pointer Pointers in structure Passing whole structure to function PU 2006 SPRING 5a) Meaning of some pointer expressions 2003 fall 4 a) Write a program with user defined function using pointers to convert all the uppercase letters to lower-case and vice versa in a string given by the user

SOME CONCEPTUAL TERMS Returning multiple value by functions Program documentation Important casting mechanism Variables Call by value vs. call by reference A simple program demonstrating structure: It takes data and print info of whose address is “pokhara”

FILE HANDLING File pointer vs. std

PU2009 SPRING 6 b) WAP to read name, author and price of 500 books and store the info to “library.dat” and print info of books of price > 300 PU2009 FALL 6 b) Create a structure for the following data: Id, Name, Address, Salary, Date of join and write program to input 100 employee, save in emp.dat file then print info of employee who have the address 'pokhara' Due fee Prints student info whose due fee is less than 100 PU2002 Consumed charged data merged with file handling: WAP that stores following data of customer of electricity authority in file ‘elect.dat’: id, name, old reading, new reading and amount to be paid

PROJECTS Books Phone book Mark sheet by harder method Mark sheet by easier method Updated mark sheet Stores Updated stores

You can get soft copy of this book @ www.scribd.com/dpalikhe You can get soft copy of this book @ www.scribd.com/dpalikhe You can get soft copy of this book @ www.scribd.com/dpalikhe

PROGRAMMING ANALYSIS IN C SOME BEGINNING PROGRAMS DECISION MAKING While going to the solution of a problem, we encounter many problems to which small decisions or a group of small decisions or a loop of small decision can give a meaningful output. As much as possible, decisions must be easier, simpler to read, understand and analyze being in great purpose to the problem’s solution.

LOOP One of the important processes in C programming is the repetition of statements (same for all time or change gradually with time or condition or variables or inputs supplied by users, etc.). The array is based on this looping (especially dynamic array).

A PROGRAM TO CONVERT DEGREE CELCIUS TO FAHRENHEIT //A PROGRAM TO CONVERT DEGREE CELCIUS TO FAHRENHEIT #include #include int main() { int celcius, fahrenheit; clrscr(); printf("Enter temperature in celcius\t"); scanf("%d",&celcius); fahrenheit=(celcius*1.8)+32; printf("\n The equivalent temperature of %d in Fahrenheit is %d",celcius,fahrenheit); getch(); return 1;}

A PROGRAM TO FIND POSITIVE OR NEGATIVE We can conclude a number is positive or negative by comparing it with zero and the sum here is the previous value stored in sum plus new value need to be stored in ‘sum’ i.e. ‘sum=sum + num’. Here sum is calculated and average is calculated by dividing sum by number of items. To calculate the number of items we declared a counter whose initial value is zero and it gets incremented by one each time the second if gets executed and hence average is calculated. #include #include void main() { int n,num[100],positive=0,negative=0,i; printf("Enter how many numbers do you want to test?"); scanf("%d",&n); for(i=0;i0) { positive=positive+1; }

By Devendra Man Palikhe

1

PROGRAMMING ANALYSIS IN C else if(num[i]0){ digit= temp_num%10; temp_num=temp_num/10; sum=sum+pow(digit,3); } if(sum==num) printf("IT IS ARMSTRONG"); /*to preserve originality necessary for comparison 'num' holds original value */ else printf("IT IS NOT ARMSTRONG"); getch(); } Please look ‘recursive function’ for further advancement.

EVEN AND ODD NUMBERS Find remainder by division by two using “%” (modulo division) and then and check it is 0 or not, if 0 then even else odd. #include #include #include void main() { int num; clrscr(); printf("Enter a number"); scanf("%d",&num); if(num%2==0) printf("IT IS EVEN"); else printf("IT IS ODD"); getch(); }

By Devendra Man Palikhe

7

PROGRAMMING ANALYSIS IN C We generally use ‘for-loop’ to add limiting values for numbers to be checked. Let’s us look a small program that prints even numbers from 107 to 221 and prints sum of odd numbers of the given range. #include #include #include void main() { int odd_sum=0,i; printf("The even sumbers are\n"); for(i=107;i0;i++) { digit=num%10; num=num/10; int temp=digit*pow(10,i);

By Devendra Man Palikhe

15

PROGRAMMING ANALYSIS IN C printf("\n%d is added to%d",temp,lastdigit); lastdigit=digit*pow(10,i)+lastdigit; } printf("\nThe supplied number was%d",lastdigit); getch(); }

PALINDROME FOR STRING Similar to palindrome numbers, palindrome strings are those strings in which characters glanced from front is equal to glanced from back. For e.g. radar, madam, yagay, eye, eve.

1. Using reversing string function

16

#include #include #include void main() { char string[10]; char temp[10]; printf("Enter a String"); scanf("%s",string); strcpy(temp,string); strrev(string); if(strcmp(temp,string)==0) printf("\nThe String is Palindrome"); else printf("\nThe String is not Palindrome"); getch();} OR #include #include void main() { char string[100],comp[100]; printf("Enter a String"); scanf("%s",string); strcpy(comp,string); strrev(string); if(strcmp(comp,string)==0){ printf("\nThe String is Palindrome"); } else { printf("\nThe String is not Palindrome");

By Devendra Man Palikhe

PROGRAMMING ANALYSIS IN C } getch();} Here ‘temp’ variable is for transition case and sudden change in ‘string’ before comparison.

2. A char[] is declared where each time a new last character from string is taken one by one as array and then checking is done to original string #include #include #include #include int main() { int i; char temp[2]; char string[30]="",newstring[30]=""; printf("Enter a String"); scanf("%s",string); for(i=strlen(string)-1;i>=0;i--) { temp[0]=string[i]; strcat(newstring,temp); } if(strcmp(newstring,string)==0){ printf("hello.........."); printf("the String is Palindrome"); } else { printf("hello"); printf("\nThe String is not Palindrome"); } getch(); return 0; }

Here the ‘newstring’ is to hold old value which is every time concatenated with new value.

3. Palindrome for string containing even or odd quantity of characters This method uses the property of even and odd in palindrome that half alphabets taken from front if equals to half alphabets taken from back then it is palindrome. But for odd (half-1/2) is compared because the central alphabet is always constant as its pace from front is equal to from backward. For e.g. In case of even number of characters containing string like “YAGGAY”, here we need to read first three characters from ‘Y’ to ‘G’ and store in ‘front’ variable then we need to read last three characters from ‘Y’ to ‘G’ in reverse manner and store in ‘reverse’ variable. If ‘reverse’ is same to ‘front’ variable then it is palindrome, for the particular case it is palindrome.

By Devendra Man Palikhe

17

PROGRAMMING ANALYSIS IN C In case of odd numbers of characters containing string like “YAGAY”, here we need to read first two characters “YA” and store it in ‘front’ and similarly read last two characters “YA” in reverse manner and store in ‘reverse’ and comparison is done. Here the central character “G” holds the same value for the same position when read either from front or from reverse, so the comparison for this central character is rejected from ‘front’ and ‘reverse’ variables.

#include #include #include void main() { int i; char string[100],front[100]="",reverse[100]=""; printf("Enter a String"); scanf("%s",string); if(strlen(string)%2==0){//for case of even strncat(front,string,strlen(string)/2); strncat(reverse,strrev(string),strlen(string)/2); } else {//for case of odd strncat(front,string,(strlen(string)-1)/2); strncat(reverse,strrev(string),(strlen(string)-1)/2); } if(strcmp(front,reverse)==0) printf("\nThe String is Palindrome"); else printf("\nThe String is not Palindrome"); getch();}

4. Palindrome for string using for-loop #include #include #include int main() { int i; char string[100]="",newstring[100]=""; printf("Enter a String"); scanf("%s",string); static char temp[1]; for(i=(strlen(string)-1);i>=0;i--) { temp[0]=string[i]; strcat(newstring,temp); } if(strcmp(newstring,string)==0){ printf("\nThe String is Palindrome");} else{ printf("\nThe String is not Palindrome");

By Devendra Man Palikhe

18

PROGRAMMING ANALYSIS IN C } getch(); return 0;}

ELECRTICITY AUTHORITY An electricity board charges according to the following rates: Units Charges (In NRs.) 0-100 40 101-200 50 201-ABOVE 60 All users are also charged ‘meter charge’, which is equal to Rs. 50. Write a complete C program to read the number of units consumed and print out the total charges. Here the first condition is to check whether the unit is within range 0 to 100 or 101 to 200 or 201 to above. After this we calculate the charge for units above higher maximum range then the units is reduced for lower range continuously whereas on the other hand, charge is added systematically from higher to lower level. Here ‘goto’ has a special purpose of direct connection. It connects higher range to lower range before this, units of higher are reduced to lower because ‘goto’ sends to lower where calculations of lower range only is necessarily to be done. /*ELECTRICITY AUTHORITY CHARGES AS FOLLOW Units Charges (In NRs.) 0 to100 R.s.40 101 to 200 R.s.50 201to ABOVE R.s.60 AND IT TAKES Rs. 50 as meter charge. A PROGRAM THAT INTAKE UNITS CONSUMED AND FIND OUT TOTAL CHARGE.*/ #include #include void main() { int units=0,charge=0,choice=0,totalcharge=0; printf("ELECTRICITY AUTHORITY CHARGES AS FOLLOW\nUnits----Charges (In NRs.)\n0 to100 R.s.40\n\n101 to 200 R.s.50\n\n201to ABOVE R.s.60\n\nAND IT TAKES Rs. 50 as meter charge\n"); printf("\nEnter Units Consumed\t"); scanf("%d",&units); int old=units; if(units>200){ choice=200; } else if(units>100){ choice=100; } else { choice=0; }

By Devendra Man Palikhe

19

PROGRAMMING ANALYSIS IN C switch (choice){ case 200: charge=(units-200)*60; units=200; totalcharge=charge; printf("\nAbove '200' units i.e. 201 to %d (%d * 60)= %d",old,old-200,charge); old=200; goto A; case 100: A: charge=(units-100)*50; totalcharge=totalcharge+charge; units=100; printf("\nAbove '100' units i.e. 101 to %d (%d * 50)= %d",old,old-100,charge); old=100; goto B; case 0: B: charge=units*40; totalcharge=totalcharge+charge; printf("\nAbove '0' units i.e. 0 to %d (%d * 40) = %d",old,old-0,charge); totalcharge+=50; printf("\n Meter Charge = %d",50); break; default: printf("Invalid Input"); } printf("\n-------------------------------------------------------"); printf("\nThe total cost of power consumed is NRs. %d",totalcharge); getch(); }

We can improve its continuity by adding a line and a index using ‘goto’ statement, like this. /*ELECTRICITY AUTHORITY CHARGES AS FOLLOW Units Charges (In NRs.) 0 to100 R.s.40 101 to 200 R.s.50 201to ABOVE R.s.60

By Devendra Man Palikhe

20

PROGRAMMING ANALYSIS IN C AND IT TAKES Rs. 50 as meter charge. A PROGRAM THAT INTAKE UNITS CONSUMED AND FIND OUT TOTAL CHARGE.*/ #include #include void main() { printf("ELECTRICITY AUTHORITY CHARGES AS FOLLOW\nUnits----Charges (In NRs.)\n0 to100 R.s.40\n\n101 to 200 R.s.50\n\n201to ABOVE R.s.60\n\nAND IT TAKES Rs. 50 as meter charge\n"); int units=0,charge=0,choice=0,totalcharge=0; maina : printf("\nEnter Units Consumed\t"); scanf("%d",&units); int old=units; if(units>200){ choice=200; } else if(units>100){ choice=100; } else { choice=0; } switch (choice){ case 200: charge=(units-200)*60; units=200; totalcharge=charge; printf("\nAbove '200' units i.e. 201 to %d (%d * 60)= %d",old,old-200,charge); old=200; goto A; case 100: A: charge=(units-100)*50; totalcharge=totalcharge+charge; units=100; printf("\nAbove '100' units i.e. 101 to %d (%d * 50)= %d",old,old-100,charge); old=100; goto B; case 0: B: charge=units*40; totalcharge=totalcharge+charge; printf("\nAbove '0' units i.e. 0 to %d (%d * 40) = %d",old,old-0,charge); totalcharge+=50; printf("\n Meter Charge = %d",50); break; default: printf("Invalid Input"); } printf("\n-------------------------------------------------------"); printf("\nThe total cost of power consumed is NRs. %d",totalcharge); printf("\n\n do you continue\n press 1 to continue");

By Devendra Man Palikhe

21

PROGRAMMING ANALYSIS IN C if(getch()=='1') { goto maina;} }

Here ‘maina’ index repeats the statements only if ‘1’ value is entered. ‘getch()’ takes a character so ‘1’ is user to make 1 as character. PU2006SPRING 3b) Electricity board charges according to the following rates. For the first 100 units -------------------------- Rs. 40 per unit For the next 200 units ------------------------- Rs. 50 per unit Beyond 300 units ------------------------------ Rs. 60 per unit All users are also charged ‘meter charge’, which is equal to Rs. 50. Write a complete C program to read the number of units consumed and print out the total charges. Next analyzing way in a little bit detail #include #include /* units range cost 301 Rs. 60 101 - 300 Rs. 50 1 - 100 Rs. 40 */ void main() { float units=0,cost=0; printf("\nEnter Units Consumed:\n"); scanf("%f",&units); if(units>300) { cost=100*10+200*50; units=units-300;

By Devendra Man Palikhe

22

PROGRAMMING ANALYSIS IN C cost=cost+(units*60); } else if (units>100) { cost=100*40; units-=100; cost=cost+(units*50); } else { cost= units*40; // the only last possible condition units>0 } cost=cost +50;//we can replace it by using this to each blocks of if-elseif ladder /*In scase instead of 50 as charge if 15% is taken as any kind of sharge like meter charge or vat then 'cost=115/100*cost' or'cost=cost+(15/100*cost)' can be used*/ printf("The total cost of %f units is %f",units,cost); getch(); } --------------------------------------------program termination---------------------------------------------Next view for analyzing problem in next way but for these no real program codes are written /* units range cost 1 - 100 Rs. 40 101 - 300 Rs. 50 301 Rs. 60 */ if(units
3

0

2

1

1

0

1

So 12 0 = 1100  Here ‘factor’-variable works as a multiplier to obtain appropriate numbers of appropriate digits, please refer ‘Digits taking from number’ for further. // decimal to binary #include #include int main() { int deci; int r; int sum=0; int factor=1; printf("enter decimal number\t"); scanf("%d",&deci); while(deci>0) { r=deci%2; deci=deci/2; sum=sum+r*factor; factor*=10; } printf("The answer is %d",sum); getch(); return 0; }

Binary to decimal 1100=1 ∗ 2 + 1 ∗ 2 + 0 ∗ 20 +(0*2 ) // binary to decimal #include #include #include int main() {

By Devendra Man Palikhe

59

PROGRAMMING ANALYSIS IN C int bina; int digit; int sum=0; int i=0; printf("enter binary number\t"); scanf("%d",&bina); while(bina>0) { digit=bina%10; bina/=10; sum=sum+digit*pow(2,i); i++; } printf("The answer is %d",sum); getch(); return 0; }

Exclusive use of ‘switch-case’ and ‘goto’ statements 2005PU

A program that takes a sum of money and starts converting it to smaller units where user can choose his first starting unit. The conversion is in such a way that the first starting units takes maximum possible conversion then the left sum is supplied to conjugate term following it, this process continues till the end. #include #include int main(){ int currency; int choice; int m; printf("Enter currency\t"); scanf("%d",¤cy); printf("\n Enter 1000 to start from 1000"); printf("\n Enter 500 to start from 500"); printf("\n Enter 100 to start from 100"); printf("\n Enter 50 to start from 50"); printf("\n Enter 20 to start from 20"); printf("\n Enter 10 to start from 10"); printf("\n Enter 5 to start from 5"); printf("\n Enter 2 to start from 2"); printf("\n Enter 1 to start from 1"); printf("-----------------------------------------------\n\n\n\n"); scanf("%d",&choice); switch (choice) { case 1000: goto thousand;

By Devendra Man Palikhe

60

PROGRAMMING ANALYSIS IN C case 500: goto fivehun; case 100: goto hundred; case 50: goto fifty; case 20: goto twenty; case 10: goto ten; case 5: goto five; case 2: goto two; case 1: goto one; }

thousand: m=currency/1000; currency=currency%1000; printf("The no. of thousands(1000) is\t\t\t%d\n",m); goto fivehun; fivehun: m=currency/500; currency=currency%500; printf("The no. of five hundreds(500) is\t\t\t%d\n",m); goto hundred; hundred: m=currency/100; currency=currency%100; printf("The no. of hundreds(100) is\t\t\t%d\n",m); goto fifty; fifty: m=currency/50; currency=currency%50; printf("The no. of fifty(50) is\t\t\t%d\n",m); goto twenty; twenty:

By Devendra Man Palikhe

61

PROGRAMMING ANALYSIS IN C m=currency/20; currency=currency%20; printf("The no. of twenty(20) is\t\t\t%d\n",m); goto ten; ten: m=currency/10; currency=currency%10; printf("The no. of ten(10) is\t\t\t%d\n",m); goto five; five: m=currency/5; currency=currency%5; printf("The no. of five(5) is\t\t\t%d\n",m); goto two; two: m=currency/2; currency=currency%2; printf("The no. of two(2) is\t\t\t%d\n",m); goto one; one: m=currency/1; currency=currency%1; printf("The no. of one(1) is\t\t\t%d\n",m); getch(); return 1; }

The general mechanism of each block of indices like ‘fifty:’ ’five hun:’….. checks whether the sum of money left for it after preeceeding calculations; are sufficient enough to hold that value or not. If yes then it does calculation. Here calculation means subtracting the left sum by the respective amounts

By Devendra Man Palikhe

62

PROGRAMMING ANALYSIS IN C and then ‘goto-statement’ transfers the execution flow to next succeeding block of indices until last index ‘one:’. Here ‘m=variable’ gives the quantity of each amount in each block. At first user is given choice to start converting money from what bigger amount of sum like from 500 or 1000 or 100 or 50 or any. So the above mechanism starts from the respective block only. Here ‘swich-case’ is used to meet user’s choice in various alternatives. If someone wants to coiunt money from 500 then the sum he enters will not be counted from 1000 instead it will be counted from 500 then 100 then 50 then 20 then 10 then5 then 2 and finally 1. It is not necessary that all blocks assume some value because the sum we enter are divisible for some; not for other and even if it is divisible the sum to be calculated on a block changes from block to block as the calculation begins.

SORTING

Selection sorting Algorithm (for ascending) •

Compare a [1] with second element a [2]. If a [2] is smaller than a [1] then interchange their values.



Compare a [1] with a [3]; interchange their values if a [3] is smaller than a [1].



Continue comparing a [1] with other numbers.



Repeat above processes (1, 2 and 3) for a[2],a[3]………a[n-1] comparing a[2] from a[3] to a[n], a[3] from a[4] to a[n]………a[n-1] with a[n].

In the repeated trips the each element compares with other remaining elements coming after it and the smallest numbers come up directly by selection (or it may step up wisely by co-incidence). Hence it is called selection sorting as each element compares with the other. Actually, there is the comparison of no element but there is the comparison of elements of specified addresses. Elements don’t change, however their addresses change. So in sorting, comparison is between addresses that take values as per condition; that is suited for the purpose-ascending or descending. Here each loop decides the comparison of element of an address to the other addresses but not of all addresses. So the inner loops successively give the necessary sorting. The trend of loops goes on decreasing from (n-1) to1 because as the loop continues each time, each address gets secured on its position.

We have started comparing numbers from j=0 to j=n-1 so the address (1) gets secured and then in next i=1 address (2) gets secured and so on. If we had started from j=n to j=2 (similarly to above case, here j=1 automatically secured after last loop because according to the sense we know any number of things can change their physical property; place in reference to a single thing or with reference to a body, others can only change in regard to the values they posses, not on the specific places they posses and hence in above case j=1 is not taken) the addresses of j=n first gets secured then j=n-1, j=n-2……j=2 and j=1 automatically gets secured.

By Devendra Man Palikhe

63

PROGRAMMING ANALYSIS IN C While the outer loop, is to supply each number (or actually each address) at a time which can be altered in any positions of numbers from 1 to n-1 or n to 2. Here one is not taken this is the similar case described above because one becomes our reference address again.

Work of outer loop (i) is to just facilitate each numbers each time except the reference address. Work of inner loop (j) is to compare each address (pointer) with the other taking a reference address. The result won’t alter if we take under consideration- the comparison of reference address but a good program minimizes the working time and process and in other proper understanding of pointers is the input for this program. So we don’t take the reference pointer under consideration.

You can get soft copy of this book @ www.scribd.com/dpalikhe. Illustration of Selection Sort of four items

64

In each trip, a value gets secured (or a pointer gets secured). The number of comparisons= (n-1) + (n2) + (n-3) +………1 Sum of (n-1)……….1 is n (n-1)/2

[NOTE: Actually, we directly don’t declare reference pointer but on our assumptions, automatically the reference pointer is achieved. We need to analyze it for more efficiency of the program.]

By Devendra Man Palikhe

PROGRAMMING ANALYSIS IN C For descending we can simply change the condition; inverse the condition. NOTE: Examples are done in coming using selection and bubble sorting.

Bubble sorting For ascending, •

Compare first two elements a [1] and a [2]. If a [2] is smaller than a [1], interchange their values.



Compare a [2] and a [3]; interchange them if a [3] is smaller than a [2].



Continue for all values serially.



Repeat above (1, 2, and 3) for (n-1) times.

In repeated trips through the array, the smallest elements ‘bubble up’ to the top one step at one loop (inner loop). Because of this bubbling up effect, this algorithm is called bubble sorting. Ilustratration of Bubble Sort of four items

65

In each trip, the smallest number ‘10’ shifts one position up at the end of trips. The number of comparisons = n (n-1)/2 In above,

By Devendra Man Palikhe

PROGRAMMING ANALYSIS IN C 4(4-1)/2 = 3+2+1 6=6 proved For Descending, change if (a[j]>a [j+1]) {

to

if (a[j]