Monday, November 5, 2012

Quality Policy: Definition & Examples

Juran defines Quality Policy as "Overall intentions and direction of an organization with regard to quality, as formally expressed by top management." 

Words to notice in this definition are intention and direction.
Below are few examples of Quality Policies:

Kinetic India:

" We shall strive to deliver products to meet and exceed Customer expectations of Quality, Delivery and cost "

This policy shall be deployed through
Continual improvement in product quality by process control & variability reduction.
Up gradation of manufacturing technology and skills
Cost reduction through elimination of waste in all Business processes.
Development of Human Resources
Development and participation of our suppliers

Tata Motors

Tata Motors is committed to maximizing customer satisfaction and strives to achieve the goal of excellence through ongoing development; manufacture and sale of reliable, safe, cost effective, quality products and services of international standards, by using environmentally sustainable technologies for improving levels of efficiency and productivity within its plants and ancillaries.

Tata Motors also has a commitment towards improving the quality of life of its employees, both within and outside its plants and offices, through improved work practices and social welfare schemes.

Toshiba Electron Tubes and Devices

1. We shall conduct quality-related activities in order to provide customers with the best possible products.
2. We shall observe all relevant laws, regulations, and contracts, and make efforts to continuously improve quality. By ensuring the quality and safety of our products, we will meet our customers' requirements and increase customer satisfaction.
3. We shall establish a quality management system and work to continuously improve the system.
4. We shall do our best to provide products of consistent quality. We shall investigate and identify the root cause of any inconsistencies based on data,and make all required improvements in order to ensure consistent quality.

Dabur Research Foundation

We are committed to quality compliances in all our deliverables.
-Consistent and Continuous Quality Management.
-The Management is fully committed to Quality and ensures all resources to accomplish this task.
-We value our 4C's- Compliance, Credibility, Consistency and Confidentiality.
-At DRF, Quality is a relentless commitment to continuous improvements in processes and systems, to provide consistent quality services to meet our customer requirements.

L&T Electricals Saudi Arabia Co. Ltd

It is our policy to:
-Deliver Electrical products and services meeting or exceeding customer requirement and expectation while improving value to stakeholder.
-Comply with statutory and regulatory requirements related to product, services, health & safety.
-Achieve operational efficiency by attaining productivity and profitability.
-Encourage development and involvement of employee at all level.
-LTESA management is fully committed to implement Quality Management System and continually improve its effectiveness in the organization.




Friday, October 12, 2012

References In Excel

In formulas references to cells or locations are excel are used. 

What kind of references are there in excel?

Referencing in the same sheet:

Relative: Ex. A1, B1 in the formula =A1*B1 written in the cell C1 is a relative reference. If you will copy paste this formula from cell C1 to C2 the formula will be pasted as =A2*B2 i.e. relative to the positioning of C2, excel is smart enough to find the relative quantities that have to be multiplied. 

Absolute: Ex. $A$1, $B$1 etc is absolute positioning. Why would you absolute positioning? One of the many possible cases is when the formula uses some constant say pi(=22/7). If you have put the value of constant at position say, A1 then you can refer to this constant in all the formulas by $A$1. When you copy paste formula from a cell in this case the $A$1 reference remains unchanged.

Row Absolute: Ex. A$1, B$1 etc i.e. only column will change, row is fixed as 1.

Column Absolute: Ex. $A1, $B1 etc i.e. only row will change, column is fixed as 1.

Referencing to a cell in other worksheet:
The general way is by using 'sheetname'!cell.
Ex: 'Sheet1'!A2

Referencing to cell in other workbook:
'[workbookname.xls]sheetname'!cell
Ex: '[Expenditure.xls]Household'!B3

If the workbook we are referencing to is closed then we have to give its path too as:
'D:\ExcelPractice\[workbookname.xls]sheetname'!cell

Thats it about referencing for now.


PS: Corrections/Suggestions/Comments are welcome!

Excel: Random Stuff Part 1

To write same thing on multiple cells
1. Select a range of cells say from A1 to A10 
2. Write whatever you want to write
3. Press Ctrl+Enter

If what you want to write is already there in a cell and you want to copy it in cells adjacent to it 
1. Select the cells where you want the text
2. Select the cell which has the required text
3. Press F2
4. Press Ctrl+Enter

To copy a cell contents on the cell to the right, 
1. Select the range of cells 
2. Press Ctrl+R

To copy a cell contents on the adjacent cells below, 
1. Select the range of cells 
2. Press Ctrl+D

To write a fraction 
1. Write 0 followed by a space and the fraction with the slash
2. Press Enter

Use TAB or Enter to move in a selected range of cells

To edit contents of cell Press F2 and it takes you in the cell

To convert a formula into its numerical value 
1. Go in the cell 
2. Press F2
3. Select the formula or part of the formula which you want converted
4. Press F9
5. Press Enter
This method loses the formula while retaining the calculated value.

To compare values in two cells
1. Use expression like =A1=B1, =A1>B1, =A1<B1
2. It returns either True or False

Table of Operators in Excel



And and Or in Excel
=OR(A1=100, A1=200) returns TRUE if either of A1=100 or A1=200 holds else FALSE

=AND(A1<100, A2>200) returns TRUE if both A1<100 and A2>200 holds else FALSE


Operator Precedence in Excel


Calculating Formulas
If calculation mode (Formulas>Calculation>Calculation Options) is set manual then:
Press F9 to recalculate the sheet

scanf() Infinite Loop

Every call to scanf picks up from where the last one stopped matching the input.  This means that if an error occurred with the previous scanf, the input it failed to match is still left unread, as if the user typed ahead.  If care isn't taken to discard error input, and a loop is used to read the input, your program can get caught in an infinite loop.

(Source: http://wpollock.com/CPlus/PrintfRef.htm)

You can also use flushall(); within the loop and before calling the scanf to tackle this problem.


Thursday, September 13, 2012

Capitalize First Letter Of Sentences

Compiler Used: TurboC
Language: C

This program demonstrates how to read file contents from c.txt, capitalize first letter of every sentence and then write it to d.txt.


//capitalize first letter of every sentence
//after every fullstop capitalize the first alphabet encountered
#include<stdio.h>
#include<conio.h>

void main(){
clrscr();
int cap=1;
char c;
FILE *fp1, *fp2;

fp1 = fopen("c.txt", "r");
fp2 = fopen("d.txt", "w");
while((c=getc(fp1))!=EOF){
if(c == '.'){
cap =1;
}
if(cap ==1 && c >=97 && c<=122){
c = c-32;
cap =0;
}
putc(c, fp2);
}
rewind(fp1);
while((c=getc(fp1))!=EOF){
 putchar(c);
}
printf("\n\n");
fclose(fp1);
fclose(fp2);
fp2 = fopen("d.txt", "r");
while((c=getc(fp2))!=EOF){
    putchar(c);
}
getch();
}

Here is what output looks like:

You can see contents of c.txt has been copied to d.txt and first letter of every sentence has been capitalized.

PS: Improvements/Suggestions/Comments on the program are welcome. I am sure there are better ways to do it.

Convert File Contents To Uppercase In C

Compiler Used: TurboC
Language: C

This program copies content from a.txt converts it into uppercase and writes it to file b.txt.


#include<stdio.h>
#include<conio.h>

void main(){
clrscr();
char c;
FILE *fp1, *fp2;
fp1 = fopen("a.txt", "r");
fp2 = fopen("b.txt", "w");
while((c = getc(fp1))!=EOF){
//printf("%c", c);
//getch();
if(c>=97){
 c = c-32;
}
putc(c, fp2);
}
fclose(fp1);
fclose(fp2);
fp2 = fopen("b.txt", "r");
while((c=getc(fp2))!=EOF){
 putchar(c);
}
fclose(fp2);
getch();
}

PS: Comments/Suggestions/Improvements are welcome.

Copying From One File To Another In C

Compiler Used: TurboC
Language: C

This is a simple program to demonstrate file handling in C by copying contents of a.txt to b.txt and displaying on the screen.


#include<stdio.h>
#include<conio.h>

void main(){
clrscr();
char c;
FILE *fp1, *fp2;

fp1 = fopen("a.txt", "r");
fp2 = fopen("b.txt", "w");
while((c = getc(fp1))!=EOF){
        putc(c, fp2);
}
fclose(fp1);
fclose(fp2);
fp2 = fopen("b.txt", "r");
while((c=getc(fp2))!=EOF){
        putchar(c);
}
fclose(fp2);
getch();
}

PS: The program can be made better in a lot of ways. Suggestions/Comments are welcome.

Sunday, September 9, 2012

Understanding The Switch Statement

Basic Syntax:

switch(some-expression){
case some-constant1:
/* some code*/
break;


case some-constant2:
/* some code*/
break;


default:
/*some code*/
break;
}

Now important points worth noting are:

  1. some-expression in the switch(some-expression) can be an expression, a constant or a variable
  2. In the cases within switch construct, some-constant are constant integer values. Floats and expressions are not allowed here
  3. break; is optional
  4. default case is also optional
Interesting cases arise when break; are not used. Look at the following example:



switch(1*3-1){
case 1:
printf("\nThis is case 1.");


case 2:
printf("\nThis is case 2.");


case 3:
printf("\nThis is case 3.");

default:
printf("\nThis is default case.");
}

If you run this the output is:

This is case 2.
This is case 3.
This is default case.

So you can see that switch goes directly to the case indicated by the value of some-expression and then keeps on executing statements until a break; is encountered or until the end of the construct.

PS 1: Compiler used is TurboC
PS 2: Corrections/Suggestions/Comments are welcome.

Wrong Input Through scanf, What Happens?

scanf does not assign the value entered in case of wrong input.

Go through the following lines of code:

#include<stdio.h>
#include<conio.h>

void main(){
int x=100;
scanf("%d", &x);
printf("Value of x is = %d", x);
getch();
}

Now the scanf is supposed to scan an integer value. Take 2 cases where you input:
(i) 2
(ii) d (or any character)

In (i) printf prints Value of x is = 2.
In (ii) printf prints Value of x is = 100.

Note that when you give wrong input to scanf, it does not assign any value to x and so the previous value of x is retained.

PS1: Compiler used TurboC.
PS2: Corrections/Suggestions/Comments are welcome!

What Does printf & scanf return?

printf returns the number of characters it prints. 

Examples:
If you write an expression like:
x = printf("%s", "Muttley is awesome!"); or
y = printf("%d", 1111);
then, what does printf return to x and y?

x = 19 and y = 4.

scanf returns the number of items it scans. However it stops scanning as soon as you give wrong input.

Examples:
p = scanf("%d%d%d", &y, &z, &w);
r = scanf("%d%d", &y, &z);

If all inputs are correct in the expression for p then, 
p = 3. Similarly, r = 2.

Lets say you give wrong third input(may be you enter a character instead of int) in the expression for p, immediately scanf stops and returns the value 2 to p. If the first input is wrong then scanf will return 0 to p.

So we can say that scanf returns the number of items scanned before the first wrong input entered. 
(Reminds me of geometric distribution)

Thursday, September 6, 2012

Small q And BIG Q


Little Q is performance to specifications, i.e. the approach that is dominant in Six Sigma and ISO 9000.

Big Q is delivering what the customer wants and exceeding those expectations. It’s the difference between tactical quality management and strategic quality management.


Big Q arose out of the realization that managing for quality should not be limited to manufacturing companies and manufacturing processes, but should also include service companies and business processes. Quality managers and upper managers have most accepted the concept of Big Q, starting in the 1980s, and the trend has been growing ever since. Time has also shown that managers in technological areas and certain staff functions have traditionally been the most resistant to it.

Big Q takes the goals of more traditional, earlier modes of quality control management (“Little q”) and builds on them. For the purposes of better understanding, let’s look at it this way: In terms of products, for example, the content of Little q would be manufactured goods, while the content of Big Q would encompass all products, goods and services, whether for sale or not. In terms of processes, Little q focuses on those processes directly related to the manufacture of goods, while Big Q covers all processes.

It has been demonstrated that since the widespread adoption of the Big Q concept in the 1980s, recognition for quality within the corporate world has increased. Quality councils have sprung up more and more to nominate and select specific projects to be recognized for their quality achievements. The scope of these nominations has increased over time, and this has been attributed to the manner in which Big Q has broadened the notions of what constitutes quality management.

Big Q has become an integral component in the business world, and is without question here to stay. We just may not call it Big Q. Some may call it TQM, some Six Sigma and others just common sense.

PS: Source- juran.com

Who Is Customer & Types Of Customers


A customer is anyone who is impacted by the product or process. Customers may be external or internal.

EXTERNAL CUSTOMERS. These are impacted by the product but are not members of the company that produces the product. External customers include clients who buy the product, government regulatory bodies, and the public (which may be impacted due to unsafe products or damage to the environment).

INTERNAL CUSTOMERS. They are impacted by the product, and are also members of the company that produces the product. They are often called "customers" despite the fact that they are not customers in the dictionary sense, that is, they are not clients.

Saturday, September 1, 2012

Measures of Central Tendency

What does it measure of central tendency mean?

Measure of central tendency is a single value that attempts to describe a set of data by identifying the central value of that set of data.

Mean

When NOT to use mean?

Mean is susceptible to outliers. Which means it is effected by extremely high and extremely low values in the data. In such situations median is preferred over mean.

Another case is when the distribution is skewed. As the data becomes skewed the mean loses its ability to provide the best central location for the data as the skewed data is dragging it away from the typical value in the direction of the skew. In this case also median is preferred measure of central tendency.

Median

Median is a value that splits the data in two equal halves.
To calculate median arrange the data in ascending order then:
1. If the number of data (n) is odd then median is (n+1)/2th value.
2. If the number of data (n) is even, median is the average of n/2 and (n/2 + 1)th value.

Median is more resistant to outliers and skewed data than mean.
If data is non-normal then it is customary to use median instead of mean.

Mode
Mode is the most frequently occurring value in the data. Normally mode is used for categorical data.

The problem with mode is that it is not unique. In case of multi-modal data which mode represents the central tendency of data set becomes a difficult question.

Mode is also not suitable measure of central tendency in case of a continuous data, especially if the data set is not large. In such cases getting a clear mode becomes a problem.

Another case may arise when the most frequent data is far away from the rest of the data. In such case mode does not give a good measure of central tendency.

Summary of when to use mean, median , mode

Type of VariableBest measure of central tendency
NominalMode
OrdinalMedian
Interval/Ratio (not skewed)Mean
Interval/Ratio (skewed)Median


PS1: Source: Laerd Statistics: Mean, Mode, Median - Measures of Central Tendency
PS2: Corrections/Improvements/Comments are welcome.

Graphs, Frequency Distributions & Histograms For Displaying Data Distributions

Distribution
Distribution of variable describes what values the variable takes and how often it takes.

Bar Graph

Bar Graph shows the amount of data that belongs to each category in proportionally sized rectangular bars.
Data from categorical variables can be summarized using bar charts.

The following Bar Graph shows the Per Capita Net State Domestic Product at Current Prices (in Rupees) for 2010-11:

Data Source: Press Information Bureau, GOI, Per Capita Net State Domestic Product


Frequency Distribution

Wolfram MathWorld describes frequency distribution as "The tabulation of raw data obtained by dividing it into classes of some size and computing the number of data elements (or their fraction out of the total) falling within each pair of class boundaries."

Using Tally is a convenient and less error prone way to make frequency distribution tables.


Histogram
Data from quantitative variables are most commonly summarized using histograms. 

How To Draw Histograms

a. What are the number of observations (N) ? 
b. What is the range of the data? Range, R = H-L, H = highest value, L= least value. 
c. Use Sturge’s rule (k = 1+3.322LogN) to find the number of classes. 
d. Find the class width. cw = R/k. 
e. Make a frequency distribution of the data using the classes, [L,L+cw], [L+cw, L+2cw],... (use tally marks to count frequencies)
f. Draw the histogram.

Notes:
1. In order to avoid getting class width as fraction we can also use the formula 
cw = (R+w)/k where w is the least count of data. If that doesn't solve the problem then we may have to round off the class width.
2. To avoid any data point falling on boundaries of classes we can define classes as,
[L-w/2, L-w/2+cw], [L-w/2+cw, L-w/2+2cw],....
Again w, here is the least count of data.

PS: Improvements/Corrections/Comments are welcome.

Descriptive Vs Inferential Statistics

Descriptive Statistics
Collection, presentation and description of data by graphs, tables and numerical summaries such as averages, variances etc.

Inferential Statistics
Interpretation of data as well as drawing conclusions and making generalizations from the data for larger group of subjects.

Population
Entire group of individuals or subjects about which we want to gain information.

Sample
A subgroup of a population from which we obtain information in order to draw conclusions for the entire population.

Parameter
It is the numerical summary for the entire population. A parameter is unknown because the entire population cannot be studied. We use the information based on a sample to arrive at the value of population parameter. The process is inferential.

Statistic
It is the numerical summary obtained from real data or sample. We can actually observe statistics. The process is descriptive.


We can roughly understand the whole process as follows:

Sample → Descriptive Statistics(statistics) → Inferential Statistics(parameters) → Population

So we take a sample, we describe it using graphs and numerical summaries like averages, variances etc then we apply inferential statistics and make generalizations about the population.


PS: Any Improvements/Corrections/Comments are welcome.

Friday, August 31, 2012

Sources, Types of Data and Scales of Measure

Data
Facts and figures collected, analysed and summarized for presentation and interpretation.

Sources of Data
Existing Sources: Reports, records, public databases, census etc
Surveys
Experiments
Observational studies

Categories of Data

Primary Data: Directly collected by the investigator. Data is collected through direct interviews, surveys, experiments etc.

Secondary Data: Data that is collected from another source. Such data has already been collected and analysed by some agency and is reused by the researcher. Secondary data is available in research papers, journals, reports, census etc.

Classification of Data

Qualitative Data
-Nominal: There is no meaningful sequence in the data, it gives only a qualitative understanding. For example male/female, married/unmarried. Nominal data usually gives categories in the data.
-Ordinal: An order exists in the data. Responses in the questionnaire of the type: very bad, bad, neutral, good, very good etc.

Quantitative Data
-Discrete Data: Data that can be counted or countable data. Usually , there is only a finite number of possible values of discrete data.
-Continuous Data: Such as measurement. Usually anything you have to use a measuring device for is continuous data. This type of data is usually associated with some sort of physical measurement.

Scales of Measure

Nominal Scale: Scale for grouping into categories. There is no intrinsic order in data. e.g. eye color. It is qualitative data.
Basic empirical operations-determination of equality.

Ordinal Scale: There is rank ordering in the data but it does not give relative size or degree of difference between the items measured. It is a scale for ordering observations from low to high with lack of measurement sensitivity.
Basic empirical operations- determination of greater or less.

Interval Scale: Scale with fixed or defined interval e.g. temperature, time etc All attributes are measurable in interval scale. Zero is arbitrarily set in this scale and negative values can also be used. e.g. temperature. Ratio of numbers on this scale are not meaningful, the differences however can be compared.
Basic empirical operations-determination of equality of intervals or differences

Ratio Scale: Data at the ratio level possess all of the features of the interval level, in addition to an absolute zero value(no numbers exist below zero). Due to the presence of a zero, the ratios of measurements can be compared. Most of the data in physical sciences and engineering belong to this scale.


PS: Suggestions/Corrections/Comments are welcome.

Statistics: Definition, Functions, Scope and Limitations

In very brief:

Definition of Statistics
Statistics is the science of collection, presentation, analysis and interpretation of numerical data.

Functions of Statistics
Condensation of Data: Statistics helps in reducing the complexity of data and consequently to understand vast amount of data. Classification and tabulation are two important methods to condense data.
Facilitates Comparison: Statistics helps in comparing data obtained from different sources.Measures of central tendency, measure of dispersion, correlation coefficients, graphs etc are tools that are used for comparison.
Draw Inferences: Statistics helps in drawing inferences about a population from the analysis of a sample drawn from that population.
Testing of Hypothesis: Tests whether a statement made on a population based on the available information is valid or not.
Forecasting: Analysis of time series and regression are some of the tools that are used to predict or estimate beforehand.

Scope of Statistics:
Industry: Control charts and inspection charts.
Commerce: Stocking of material based on the estimated demand.
Agriculture: ANOVA is used in agriculture to test the equality of different population means.
Medicine: t-tests are used to test effectiveness of a new drug or compare the effectiveness of two drugs.
Economics: Index numbers, time series analysis, hypothesis testing are widely used in economics.
Planning: Statistical data related to production, consumption, demand, investment, expenditure and advanced statistical techniques are used for making policy decisions.

Limitations:
Statistics should only be used as a supportive tool in the study of a population.
Statistical laws are not exact.
It studies characteristics of population not individuals.
Not suitable for study of qualitative phenomenon. However if such phenomenon can suitable and accurately be represented in numerical form then statistical methods can be used for study.

PS: Corrections/Additions/Comments are welcome.

How Binomial and Poisson Distributions Vary

Plotting a Binomial Distribution in Excel:
Use the function = BINOMDIST(x, n, p, TRUE/FALSE)
You have to use either TRUE or FALSE is the past parameter.
TRUE is used when you want to calculate cumulative probability, and FALSE if you want to calculate probability for a particular trial.

I used FALSE since I wanted to calculate individual probabilities for different values of x. Here is the result of what I plotted:


Plotting a Poisson Distribution in Excel:
Use the function = =POISSON(x, λ, TRUE/FALSE)
Again True is used when we want to calculate cumulative probability. If you want to calculate probability for a particular value of x use FALSE.
I used False to calculate the probabilities for different values of x. Here is the result:



Conclusions you can draw from these plots:
1. For p=0.5 binomial distribution is symmetric.
2. As p increases for fixed n, binomial appears to shift towards the right.
3. Poisson distribution tends to behave like bell curve(Normal Distribution) for large values of Î».

PS1: Excel sheet is attached in case you want to experiment and learn more.
Link:-  Probability Distributions Binomial and Poisson

PS2: Corrections/suggestions are welcom.

Thursday, August 30, 2012

Probability Distributions Used In Acceptance Sampling

In basic acceptance sampling techniques three most common distributions used are:
Hypergeometric: Parameters N, X, n
Binomial: Parameters n,p
Poisson: Parameter λ
Normal: Parameter µ, σ

Approximations

1. When N is large or n/N <0.1 then Hypergeometric (N, X, n) → Normal (n, X/N)
2. When n → ∞ and p → 0  such that np → Î» (some constant) then Binomial (n, p) → Poisson(λ)
3. For large values of λ Poisson → Normal

A hypergeometric distribution has finite population, a binomial has infinite or very large population or the experiment is done on a finite population with replacement and a poisson has infinite chances of occurrences.

PS: Corrections/Additions/Suggestions are welcome.

Infix, Prefix, Postfix

What is the need of prefix and postfix notation?
Apparently computer does understand the operator precedence but if there is a big expression like:
y = a + b*c + k/{d + e/(a+g+h*d)} - g + (e+ f/(s+t*k/(blah*klah)))/u
with lots of parenthesis' there is no way it understands which part of the expression to evaluate first.

So to make it easier for machine to interpret and evaluation expressions according to rules of mathematics which we understand implicitly, postfix and prefix notation is used.

Infix: 
The expressions that we have been seeing since kindergarten are all infix expressions. Just to refresh your memory:
3+5*6 -9 
is an infix expression. You can see all the operators in infix expression are in-between the operands.

Prefix Notation:
In prefix notation operators is written before the operands in the expression. So
A+B will be written as +AB.

How to write Prefix expressions?
Take the expression:
A-B/(C*D$E)

Step 1: You understand the small calculations you have to make in order to evaluate this expression correctly. Lets show them in parenthesis:

A-(B/(C*(D$E)))

Step 2: Now starting with the innermost parenthesis start writing the prefix expression. I'll show it in steps to make it easier to understand:
(i) A-(B/(C*(D$E)))
(ii) A-(B/(C*($DE)))
(iii) A-(B/(*C($DE)))
(iv) A-(/B(*C($DE)))
(v) -A(/B(*C($DE)))

Step 3: Remove all the parenthesis after you are done with converting the expression into prefix. We get:
-A/B*C$DE

Postfix Notation
Operators are written after the operands. Simply put:
A+B will be written as AB+

How to write Postfix expressions?
We will take the same example as above.
A-B/(C*D$E)

Step 1: You understand the small calculations you have to make in order to evaluate this expression correctly. Lets show them in parenthesis:

A-(B/(C*(D$E)))

Step 2: Now starting with the innermost parenthesis start writing the postfix form. I'll show it in steps to make it easier to understand:
(i) A-(B/(C*(D$E)))
(ii) A-(B/(C*(DE$)))
(iii) A-(B/(C(DE$)*))
(iv) A-(B(C(DE$)*)/)
(v) A(B(C(DE$)*)/)-

Step 3: Remove all the parenthesis after you are done with converting the expression into prefix. We get:
ABCDE$*/-


PS1: Better and alternate ways of thinking are always there. Do suggest some in your comments.
PS2: For reference, the document is attached: Infix, Prefix, Postfix

Wednesday, August 22, 2012

Pre-Increment, Pre-Decrement, Post-Increment & Post-Decrement in C

In our context:
Pre means the increment or decrement is done before the statement is executed.
Post means the increment or decrement is done after the statement is executed.

So,

i = ++i + i++ + i-- + ++i;
      (a)     (b)    (c)     (d)
is equivalent to the following set of statements:
i = i+1; (a)
i = i +1; (d)
i = i + i + i + i; (the statement)
i = i + 1; (b)
i = i -1; (c)

Case 1: 
So if initially the value of i was i = 10, then the value of i after the statement is executed will be:
i = 10 + 1;
i = 11 + 1;
i = 12 + 12 + 12 + 12;
i = 48 + 1;
i = 49-1;

Therefore if you use printf("%d", i) after the statement you will get 48 as the answer.

Case 2:
Now consider the case: 
j = ++i + i++ + i-- + ++i;
printf("%d", j);

Then these statements are equivalent to:
i = i+1;
i = i +1;
j = i + i + i + i; (the statement)
i = i + 1;
i = i -1;
printf("%d", j);

Therefore if i is 10 initially, 
i = 10 + 1;
i = 11 + 1;
j = 12 + 12 + 12 + 12;
i = 12 + 1;
i = 13 - 1;
printf("%d", j); will give j = 48. The final value of i in this case is 12.

PS: This logic holds for C and C++. It may differ in Java.

Sunday, August 19, 2012

Implementation Of Stack Using Arrays In C

Language: C
Compiler: Turbo C

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(){
clrscr();
int stack[10],top=-1,  choice =0, entry=0, pop, i;
//insert, delete, display, underflow, overflow
while(choice!=4){
    printf("\nChoose from one of the following options:\nPress 1 to insert a number.\nPress 2 to delete a number.\nPress 3 to display a number.\nPress 4 to exit.\n\nYour choice is? ");
    scanf("%d", &choice);
    switch(choice){

    case 1:
    clrscr();
    printf("\nPlease enter the number: ");
    scanf("%d", &entry);
    if(top==9){
    printf("\nOverflow! The stack is full.\n");
    }
    else{
    stack[++top]=entry;
    clrscr();
    printf("\nYour number has been entered!\n");
    }
    break;

    case 2:
    clrscr();
    if(top==-1){
    printf("\nThe stack is empty.\n");
    }
    else{
    pop = stack[top];
    top--;
    printf("\nThe number %d has been deleted.\n", pop);
    }
    break;

    case 3:
    clrscr();
    if(top!=-1){
        for(i=0;i<=top;i++){
        printf("%d ", stack[i]);
        }
    }
    else{
    printf("\nThe stack is empty.\n");
    }
    break;

    case 4:
    exit(0);

    default:
    clrscr();
    printf("\nInvalid Entry!\n");
    //choice =0;
    break;
    }//end of switch

}//end of while
}//end of main

PS: Many improvements are possible in the program. You are welcome to suggest them in comments! :)

Binary Search & Bubble Sort Using C

Language: C
Compiler: Turbo C

#include<stdio.h>
#include<conio.h>


void main(){
clrscr();
int array[] = {12,3,4,67,89,2,4,67,7,8}, num=0, upper =0, lower=0, limit = 10, search = 0;
printf("Enter the number to search:");
scanf("%d",&num);

//sorting
int i=0, j =0, sort = 0, swap=0;
for(i=0;i<9;i++){
    sort=1;
    for(j=1;j<10;j++){
        if(array[j]<array[j-1]){
        swap = array[j];
        array[j]=array[j-1];
        array[j-1]=swap;
        sort=0;
        }
    }
    if(sort==1){
    break;
    }

} //end of sorting
//for(i=0;i<10;i++){
//    printf("%d ",array[i]);

//}
//getch();
//algorithm for binary search
upper = limit-1;
lower=0;
while(upper>=lower){
    if(array[(upper+lower)/2]==num){
        printf("Your search is successful.");
        search =1;
        break;
    }
    else if(array[(upper+lower)/2]>num){
        upper = (upper+lower)/2-1;
           //lower = 0;
    }
    else if(array[(upper+lower)/2]<num){
        lower=(upper+lower)/2+1;
    }
}
if(search ==0){
printf("Number not found.");
}
getch();
}//end of main


PS: Many improvements are possible in the program. You are welcome to suggest them in comments! :)

A Bubble Sort Program in C

This program just demonstrates what a Bubble Sorting program looks like:
Compiler used: Turbo C
Language: C
 
#include<stdio.h>
#include<conio.h>

void main(){
clrscr();
int arr[]={10,20,30,3,6,23,4}, i=0, swap=0, sort=0, j=0;
for(i=0;i<6;i++){
    sort=1;
    for(j=1;j<7;j++){
        if(arr[j]<arr[j-1]){
        swap=arr[j];
        arr[j]=arr[j-1];
        arr[j-1]=swap;
        sort = 0;
        }//end of if statement
    }
    if(sort==1){
    break;
    }
}
for(i=0;i<7;i++){
    printf("%d ",arr[i]);
}

getch();
}

PS: Many improvements are possible in the program. You are welcome to suggest them in comments! :)

Implementation Of Circular Queue Using Arrays


Compiler used: Turbo C
Language C

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(){
clrscr();
//queue deletion from front, insertion from rear
//check for overflow/underflow
int queue[10], front=-1, rear=-1, choice=0, entry=0, i;
while(choice!=4){
    printf("\nChoose from the following options:\nPress 1 to insert.\nPress 2 to delete.\nPress 3 to display.\nPress 4 to exit.\n\nYour choice is? ");
    scanf("%d",&choice);

    switch(choice){

        case 1:

        clrscr();
        if(rear==9 && front==0 || rear==front-1){
            printf("\nOverflow! Queue is full.\n");
        }
        else if(front==-1 && rear==-1){
            printf("\nPlease enter your number: ");
            scanf("%d",&entry);
            queue[++rear] = entry;
            front =0;
            printf("\nYour number has been entered!\n");
        }
        else{   printf("\nPlease enter your number: ");
            scanf("%d",&entry);
            ++rear;
            rear=rear%10;
            queue[rear]=entry;
            printf("\nYour number has been entered.\n");
        }
        break;

        case 2:
        clrscr();
        if(rear==-1){
        printf("\nUnderflow! Queue is empty.\n");
        }
        else if(front==rear){
        printf("\nThe number has been deleted!\n");
        front=-1;
        rear=-1;
        }
        else{
        front++;
        front = front%10;
        printf("\nThe number has been deleted from the queue!\n");
        }
        break;

        case 3:
        clrscr();
        if(rear==-1){
        printf("\nThe queue is empty.\n");
        }
        else if(front<=rear){
        for(i=front;i<=rear;i++){
        printf("%d ",queue[i]);
        }
        }
        else{
        for(i=front;i<=9;i++)
        printf("%d ", queue[i]);

        for(i=0;i<=rear;i++)
        printf("%d ", queue[i]);
        }
        break;

        case 4:
        exit(0);

        default:
        clrscr();
        printf("\nInvalid Choice!\n");
        break;

    }
}//end of while
}//end of main


PS: Many improvements are possible in the program. You are welcome to suggest them in comments! :)