All 16 questions UPSC has asked on statistical software in the Statistics Optional (Paper II, Optimization Techniques) from 1996 to 2026, solved step by step – latest first.
Try them yourself first: the same questions, without solutions, are on our Optimization Techniques topic-wise PYQs page.
How we check these solutions
These are our own solutions, prepared with AI help. UPSC does not publish official answers. Every solution is checked a second way before it goes up, and says how:
- ✓ Checked by computer the numbers were worked out again independently in code (Python with NumPy/SciPy) and matched.
- ✓ Answer checked step by step for descriptive questions, every point was checked against the standard theory.
Spotted a mistake or a neater method? Tell us in the comments below or through Report an error.
Jump to a question (year · question number):
2026 · 1e 2007 · 3c 2006 · 4d 2005 · 4d 2004 · 4d 2003 · 4d 2002 · 4d 2001 · 4d 1998 · 12a 1998 · 12b 1998 · 12c 1997 · 12a 1997 · 12b 1997 · 12c 1996 · 12b 1996 · 12c
What are the key features of SPSS software? How does it compare to R software?
Solution
SPSS (Statistical Package for the Social Sciences, now IBM SPSS Statistics) is a menu-driven package for managing and analysing data, widely used in social science, market research, health and education.
Key features of SPSS.
- Two views of the data: Data View (a spreadsheet of cases × variables) and Variable View (name, type, labels, value labels, missing-value codes, measurement level).
- Point-and-click menus and dialog boxes for almost every procedure, so analyses can be run without programming; every action can also be pasted as syntax (a command language) for documentation and repetition.
- Data management: import from Excel, CSV, databases; recode, compute, select and weight cases, merge and split files, handle missing values.
- Wide range of procedures: descriptive statistics, cross-tabulation and chi-square, t-tests, ANOVA and general linear models, correlation, linear/logistic/nonlinear regression, factor and cluster analysis, discriminant analysis, non-parametric tests, reliability analysis, time series, survival analysis; add-on modules for advanced methods (complex samples, missing values, structural equations through AMOS).
- Output Viewer with formatted tables and charts (Chart Builder), exportable to Word, Excel and PDF.
- Easy to learn, with good documentation and technical support.
Comparison with R.
| Point | SPSS | R |
|---|---|---|
| Cost and licence | Commercial, paid licence | Free and open source |
| Interface | Menus and dialogs (plus syntax) | Mainly command/script based (RStudio helps) |
| Learning curve | Gentle; suits non-programmers | Steeper; needs programming |
| Range of methods | Standard methods, fixed set; add-ons cost extra | Very wide; over 20,000 packages; new methods appear first in R |
| Flexibility | Limited customisation | Fully programmable; users write their own functions and simulations |
| Graphics | Standard charts, easy to make | Highly flexible, publication-quality (ggplot2) |
| Reproducibility | Syntax files | Scripts, R Markdown/Quarto reports |
| Big data and integration | Moderate | Connects to databases, Python, C++, cloud; handles large data with packages |
| Support | Vendor support | Community support and documentation |
In short: SPSS is convenient for routine analysis by users who prefer menus; R is more powerful, flexible and free, and better for research, simulation and new methods, at the price of learning to program.
✓ Answer checked step by step Every point was checked against the documented features of IBM SPSS Statistics and of R.
Discuss some statistical problems which can be solved by using well known Statistical Software Packages like SPSS and which otherwise are difficult to solve.
Solution
Statistical software packages such as SPSS make it possible to solve problems that involve large data sets, heavy computation, iterative estimation or many variables, which are tedious or practically impossible by hand. Some examples:
Multiple regression with many variables — computing needs inversion of a matrix; with stepwise selection, diagnostics (residual plots, VIF for multicollinearity, Cook’s distance) and many observations, this is only practical by computer (Analyze → Regression → Linear).
Logistic, probit and other nonlinear regressions — the maximum likelihood estimates have no closed form and are found by iterative methods (Newton–Raphson); SPSS does this automatically.
Multivariate analysis — factor analysis and principal components (eigenvalues of large correlation matrices, rotations), cluster analysis (distance matrices for hundreds of cases), discriminant analysis, MANOVA, canonical correlation.
Analysis of variance for complex designs — factorial designs with interactions, unbalanced data, repeated measures, covariance analysis (General Linear Model), with post-hoc multiple comparisons.
Large surveys — cleaning and recoding thousands of records, cross-tabulations with chi-square tests, weighting, and complex sample designs (strata, clusters) for correct standard errors.
Non-parametric tests on large samples — exact -values for Mann–Whitney, Kruskal–Wallis, Wilcoxon, Friedman tests, which need extensive tabulation by hand.
Time series — fitting ARIMA models, exponential smoothing and seasonal decomposition, and forecasting; these require iterative estimation.
Survival analysis — Kaplan–Meier curves and Cox proportional hazards regression with censored data.
Reliability and scale analysis — Cronbach’s alpha and item analysis for questionnaires.
Simulation and resampling — generating random samples from distributions to study the sampling distribution of a complicated statistic, and bootstrap confidence intervals, which have no exact theory (see Q4).
Graphical analysis — histograms, box plots, normal probability (Q–Q) plots and scatter-plot matrices for checking assumptions.
The package removes arithmetic errors, gives results quickly, and lets the statistician concentrate on choosing the right model and interpreting the output.
✓ Answer checked step by step Every point was checked: each listed problem is one whose hand computation is impractical and which SPSS handles through a standard procedure.
Describe the use of SPSS software packages with an illustration.
Solution
Uses of SPSS. SPSS is used to enter, manage and analyse data and to present the results: descriptive statistics and frequency tables; cross-tabulations and chi-square tests; -tests and ANOVA; correlation and regression; non-parametric tests; multivariate methods (factor, cluster, discriminant analysis); time series and survival analysis; and charts. It is used in surveys, market research, social science, education, health and quality control.
Working in SPSS — the steps.
- Define variables in Variable View (name, type, labels, value labels, missing values, measure).
- Enter or import data in Data View (each row a case, each column a variable), or open an Excel/CSV file.
- Prepare data — Transform → Compute/Recode; Data → Select Cases, Sort, Merge.
- Choose the analysis from the Analyze menu and set options in the dialog box.
- Read the Output Viewer — tables and charts; export them to Word or PDF.
- Optionally paste the syntax to keep a record and re-run the analysis.
Illustration: correlation and regression. A firm records advertising spend (₹ thousand) and sales (₹ lakh) for 10 months:
| 10 | 12 | 15 | 17 | 20 | 22 | 25 | 27 | 30 | 32 | |
|---|---|---|---|---|---|---|---|---|---|---|
| 36 | 40 | 46 | 49 | 54 | 58 | 62 | 66 | 72 | 76 |
- Enter two variables, ADV and SALES, with 10 cases.
- Analyze → Correlate → Bivariate (Pearson): (SPSS reports , the two-sided -value and ).
- Analyze → Regression → Linear, Dependent = SALES, Independent = ADV. The output gives the Model Summary (, ), the ANOVA table ( test), and the Coefficients table (constant, slope, standard errors, , ), plus residual plots if requested.
Equivalent syntax:
CORRELATIONS /VARIABLES=ADV SALES /PRINT=TWOTAIL.
REGRESSION /DEPENDENT SALES /METHOD=ENTER ADV
/SCATTERPLOT=(*ZRESID,*ZPRED).The output shows a very strong positive relationship (), and the fitted line () can be used to predict sales for a planned advertising budget.
✓ Answer checked step by step We checked the illustration in Python: for the 10 pairs shown, Pearson r = 0.999, the regression line is ŷ = 18.68 + 1.77x, and the t-test of β = 0 has p < 0.001.
Let be a random sample from an distribution (, known). Let [?] be a statistic. Explain how the well-known statistical software packages like SPSS can be used to find the distribution of T.
Solution
Note on the question. The statistic is printed with a lower-case and a sum to 20; we read it as with . The powers and are real only for , so we take large compared with (so that negative values practically never occur), or use .
Why software is needed. is a sum of a complicated non-linear function of normal variables. Its exact distribution has no closed form. But because and are known, we can simulate it: generate many samples of size 20 from , compute for each, and study the resulting values. This Monte Carlo method approximates the sampling distribution as closely as we like (with replications, the error in a probability is about ).
Steps in SPSS.
- Create the replications. Make a data file with cases (say ), one per simulated sample, e.g. with an INPUT PROGRAM loop.
- Generate the sample. For each case compute 20 normal variables with the random-number function
RV.NORMAL(mu, sigma)(Transform → Compute Variable, or syntax), after fixing the seed for reproducibility (SET SEED). - Compute for each case with COMPUTE, using
**for powers andEXP. - Study the distribution of — Analyze → Descriptive Statistics → Frequencies/Explore: mean, standard deviation, skewness, kurtosis, percentiles, histogram with a normal curve, Q–Q plot; Kolmogorov–Smirnov test (Nonparametric Tests) against a normal or other fitted distribution.
- Use it — e.g. read off the 5% and 95% points of as critical values, or estimate by the proportion of simulated values above .
Illustrative syntax (, ):
SET SEED=12345.
INPUT PROGRAM.
LOOP #REP=1 TO 10000.
COMPUTE T=0.
LOOP #I=1 TO 20.
COMPUTE X=RV.NORMAL(4,1).
COMPUTE T=T + ABS(X)**2.5 * EXP(-2*ABS(X)**0.5).
END LOOP.
END CASE.
END LOOP.
END FILE.
END INPUT PROGRAM.
FREQUENCIES VARIABLES=T /FORMAT=NOTABLE
/PERCENTILES=2.5 5 50 95 97.5
/STATISTICS=MEAN STDDEV SKEWNESS KURTOSIS
/HISTOGRAM NORMAL.What to expect. Since is a sum of 20 i.i.d. terms, by the central limit theorem its distribution will be close to normal, with mean and variance , where ; the simulation confirms this and measures any skewness. (In our check with , , 100,000 simulated values of had mean about 11.27 and s.d. about 0.38, with slight negative skewness; negative occurred in only 0.003% of draws.)
✓ Answer checked step by step We checked the method in Python by simulating 100,000 values of T for μ = 4, σ = 1 and n = 20, the same steps the SPSS syntax carries out.
What are SPSS packages? Explain their uses.
Solution
What SPSS is. SPSS (Statistical Package for the Social Sciences), first developed in 1968 by Nie, Hull and Bent and now sold as IBM SPSS Statistics, is an integrated set of programs (“package”) for data management and statistical analysis. It consists of a base system and optional modules, works through menus or its own command syntax, and produces formatted tables and charts.
Components (packages/modules).
- SPSS Statistics Base — data handling, descriptive statistics, cross-tabs, -tests, ANOVA, correlation, linear regression, factor and cluster analysis, non-parametric tests, charts.
- Advanced and Regression modules — GLM and mixed models, logistic and nonlinear regression, survival analysis.
- Others — Forecasting (time series), Categories (correspondence analysis), Complex Samples, Missing Values, Exact Tests, Custom Tables; AMOS for structural equation modelling; SPSS Modeler for data mining.
Uses.
- Data management — data entry, coding, cleaning, recoding, computing new variables, merging files, handling missing data.
- Descriptive analysis — frequency tables, measures of central tendency and dispersion, cross-tabulations, graphs.
- Testing hypotheses — , , chi-square and non-parametric tests with exact -values.
- Modelling relationships — correlation, simple and multiple regression, logistic regression, ANOVA/ANCOVA.
- Multivariate analysis — factor, cluster, discriminant, canonical analysis, MANOVA.
- Forecasting — time-series smoothing and ARIMA models.
- Survey and market research — questionnaire analysis, reliability (Cronbach’s alpha), weighting, tabulation.
- Quality control and health research — control charts, survival analysis.
- Reporting — exporting publication-quality tables and charts.
Its value lies in speed, accuracy, ease of use and the ability to handle large data sets and complex methods.
✓ Answer checked step by step Every point was checked against the documented components and procedures of SPSS.
Describe the salient features of the SPSS package. Explain how to find a multiple linear regression based on p independent variables and n observations.
Solution
Salient features of SPSS.
- Data Editor with Data View and Variable View; variable and value labels; missing-value codes.
- Menu-driven analysis with dialog boxes, plus a command syntax language (Paste button) for automation and records.
- Data transformation — compute, recode, select, sort, merge, aggregate, weight cases.
- Comprehensive statistics — descriptive, inferential, regression, ANOVA/GLM, multivariate, non-parametric, time series, survival.
- Output Viewer — pivot tables and charts that can be edited and exported.
- Graphics — Chart Builder for bar, line, pie, histogram, scatter, box plots.
- Import/export with Excel, CSV, databases, other packages.
- Extensible through modules and integration with Python and R.
Multiple linear regression with independent variables and observations. (For the coefficients to be estimable we need ; in fact to estimate the error variance and test the model.)
Model: i.e. , with least squares estimate .
Steps in SPSS:
- Enter the data: one row per observation; columns , .
- Analyze → Regression → Linear.
- Put in Dependent and in Independent(s). Method: Enter (all variables), or Stepwise/Forward/Backward for variable selection.
- Statistics: estimates, confidence intervals, model fit, change, descriptives, collinearity diagnostics, Durbin–Watson. Plots: ZRESID vs ZPRED, normal probability plot of residuals. Save: predicted values, residuals, Cook’s distance.
- Click OK (or paste the syntax):
REGRESSION
/STATISTICS COEFF OUTS CI(95) R ANOVA COLLIN
/DEPENDENT Y
/METHOD=ENTER X1 X2 X3
/RESIDUALS DURBIN NORMPROB(ZRESID)
/SCATTERPLOT=(*ZRESID,*ZPRED).Reading the output:
- Model Summary — , , adjusted , standard error of the estimate .
- ANOVA — regression and residual sums of squares; tests .
- Coefficients — , standard errors, standardised betas, with d.f. and -values; VIF for multicollinearity.
- Residual plots — check linearity, constant variance and normality.
The fitted equation is then used for interpretation and prediction.
✓ Answer checked step by step We checked the regression set-up on simulated data in Python (n = 30, p = 3): the normal-equation solution (X′X)⁻¹X′y matched a standard least-squares routine, as SPSS’s REGRESSION output would.
Explain the use of SPSS package in solving statistical problems. In particular, how will you carry out two-way analysis of variance for a given data by using SPSS?
Solution
Use of SPSS in solving statistical problems. SPSS turns a statistical problem into a sequence of simple steps: define the variables, enter or import the data, choose the procedure from the Analyze menu, set options, and interpret the formatted output. It handles large data sets, does the computation exactly and quickly, checks assumptions (normality, equal variances) with tests and plots, and covers most standard methods — descriptive statistics, tests of significance, ANOVA, regression, multivariate and non-parametric methods, time series.
Two-way analysis of variance in SPSS. Suppose yield is observed for 3 fertilisers (factor A) and 2 varieties (factor B), with replicates per cell. Model:
- Data entry (long format): three columns — FERT (codes 1–3), VARIETY (codes 1–2) and YIELD — one row per observation. Add value labels to the codes.
- Analyze → General Linear Model → Univariate.
- Dependent Variable: YIELD; Fixed Factor(s): FERT and VARIETY (use Random Factor(s) for random effects).
- Model: Full factorial (main effects + interaction). With one observation per cell, choose Custom with main effects only (the interaction is then the error).
- Post Hoc: Tukey/Scheffé/LSD for FERT; Plots: FERT × VARIETY profile (interaction) plot; Options: descriptive statistics, estimates of effect size, homogeneity test (Levene).
- Click OK. Equivalent syntax:
UNIANOVA YIELD BY FERT VARIETY
/METHOD=SSTYPE(3)
/DESIGN=FERT VARIETY FERT*VARIETY
/POSTHOC=FERT(TUKEY)
/PLOT=PROFILE(FERT*VARIETY)
/PRINT=DESCRIPTIVE HOMOGENEITY ETASQ.Interpreting the output. The Tests of Between-Subjects Effects table gives, for FERT, VARIETY, FERT*VARIETY and Error: the sums of squares, d.f. (, , , ), mean squares, ratios and significance (-values). We first look at the interaction: if it is not significant, we interpret the main effects; if it is significant, we compare treatment means within each level of the other factor (simple effects) using the profile plot. Post-hoc tests then show which fertilisers differ.
✓ Answer checked step by step Every point was checked against SPSS’s GLM Univariate (UNIANOVA) procedure and the two-way ANOVA model with interaction, including the degrees of freedom in the output table.
Write briefly on the software package SPSS.
Solution
SPSS (originally Statistical Package for the Social Sciences; now IBM SPSS Statistics) is one of the oldest and most widely used statistical software packages. It was developed in 1968 at Stanford by Norman Nie, Dale Bent and Hadlai Hull, was acquired by IBM in 2009, and runs on Windows, macOS and Linux.
Structure. A Data Editor (Data View for cases × variables, Variable View for definitions), a Syntax Editor for its command language, and an Output Viewer for tables and charts. Analyses are chosen from menus (Analyze, Graphs, Transform) or written as syntax.
Capabilities.
- Data management: import/export (Excel, CSV, databases), recoding, computing, selecting, merging, weighting, missing values.
- Statistics: descriptives, frequencies, cross-tabs and chi-square, -tests, ANOVA and GLM, correlation, linear/logistic/nonlinear regression, factor, cluster and discriminant analysis, reliability, non-parametric tests, time series, survival analysis.
- Graphics: Chart Builder for all common charts.
- Extensions: add-on modules, Python/R integration, AMOS (structural equations).
Merits. Easy to learn and use; no programming needed; reliable, well-documented procedures; good presentation of output; handles large data sets; syntax allows repeatable analysis.
Limitations. Costly licence; less flexible than programming languages such as R or SAS for new or non-standard methods; some advanced methods need extra modules; users may run procedures without understanding the assumptions.
SPSS is widely used in social sciences, market research, health, education and government statistics.
✓ Answer checked step by step Every point was checked against the documented features and history of SPSS.
Describe the inter-relation amongst machine language, FORTRAN compiler, the FORTRAN source program and object code.
Solution
Machine language is the set of binary instructions that a particular computer’s processor executes directly. It is the only language the hardware understands.
FORTRAN source program is the program written by the user in FORTRAN (a high-level language) — statements such as X = A + B*C or DO 10 I = 1, N. The computer cannot execute it directly.
FORTRAN compiler is a system program (itself in machine language) that translates the whole source program into machine language. It also checks the syntax and reports errors (compile-time diagnostics), allocates storage for variables and arrays, and optimises the code.
Object code (object program) is the machine-language output of the compiler. It is then linked (by a linker/loader) with library routines (e.g. SQRT, SIN, input/output routines) to form an executable program, which is loaded into memory and run on the data.
Inter-relation.
FORTRAN source program --(input to)--> FORTRAN compiler
| translates
v
library routines --(linker)--> object code (machine language)
|
v
executable program --> run with data --> results- The source program is the input to the compiler; the object code is its output.
- The object code is in machine language, so the computer can execute it after linking and loading.
- The compiler translates once; the object program can be run many times without re-compiling. Changing the source requires re-compiling.
- Errors: syntax errors are found by the compiler; logical and run-time errors appear only when the object program runs.
(In contrast, an interpreter translates and executes one statement at a time and produces no object code.)
✓ Answer checked step by step Every point was checked against the standard description of compiling and linking a FORTRAN program.
Write a note on library functions available in FORTRAN IV.
Solution
Library functions in FORTRAN are built-in (intrinsic or supplied) subprograms that compute standard mathematical and conversion functions. They are used by writing the function name with its argument(s) in an expression, e.g. Y = SQRT(X) + ALOG(Z). The compiler links the corresponding routine from the system library. In FORTRAN IV the type of the function is fixed by its name: names beginning with I–N return integers, others real; double-precision versions begin with D, complex versions with C.
Common FORTRAN IV library functions.
| Function | Name (real) | Double precision | Integer / other |
|---|---|---|---|
| Square root | SQRT(X) |
DSQRT |
— |
| Exponential | EXP(X) |
DEXP |
— |
| Natural log | ALOG(X) |
DLOG |
— |
| Common log | ALOG10(X) |
DLOG10 |
— |
| Sine, cosine (radians) | SIN(X), COS(X) |
DSIN, DCOS |
— |
| Tangent | TAN(X) (later versions) |
DTAN |
— |
| Arc tangent | ATAN(X), ATAN2(Y,X) |
DATAN |
— |
| Hyperbolic tangent | TANH(X) |
DTANH |
— |
| Absolute value | ABS(X) |
DABS |
IABS(I) |
| Maximum / minimum | AMAX1, AMIN1 |
DMAX1, DMIN1 |
MAX0, MIN0 |
| Remainder | AMOD(X,Y) |
DMOD |
MOD(I,J) |
| Transfer of sign | SIGN(X,Y) |
DSIGN |
ISIGN |
| Positive difference | DIM(X,Y) |
— | IDIM |
| Truncation | AINT(X) |
— | INT(X), IFIX(X) |
| Type conversion | FLOAT(I) (integer → real) |
DBLE(X), SNGL(D) |
IFIX(X) (real → integer) |
| Complex | REAL(C), AIMAG(C), CMPLX(X,Y), CONJG(C), CABS(C) |
Rules for use.
- The argument must be of the correct type and in the valid range (e.g.
SQRTandALOGneed non-negative / positive arguments; trigonometric functions use radians). - Arguments may be constants, variables, expressions or other function references:
Z = EXP(-X*X/2.0)/SQRT(2.0*3.14159). - The function name must not be used as a variable name in the same program unit.
- A function returns a single value and can appear wherever an expression of that type can.
(FORTRAN 77 later introduced generic names, so LOG, SQRT, ABS, MAX work for any numeric type.)
Example. The normal density at :
X = 1.5
F = EXP(-X*X/2.0) / SQRT(2.0*3.14159265)
WRITE (6,10) X, F
10 FORMAT (1X, 'F(', F4.1, ') =', F8.5)gives F( 1.5) = 0.12952.
✓ Answer checked step by step Every listed function and its argument type was checked against the FORTRAN IV (and FORTRAN 77 generic) intrinsic function lists; the example was compiled and run with gfortran.
Write a FORTRAN program to evaluate the following sum:
Solution
Note on the question. The printed sum runs over to 10 but the terms are in , and at the factor is 0. We take the index to be and the ten terms : (If the intended limits are to 10, change the DO-loop limit from 11 to 10.)
Points to note.
- must be computed in real arithmetic (
N/2.0);N/2would be integer division. - is converted to real with
FLOAT. - is obtained as
(-1.0)**N(or by switching a sign variable each time).
Program.
C EVALUATE S = SUM OF (-1)**N * X**(N/2) / (N*(N-1)), N = 2 TO 11
READ (5,*) X
S = 0.0
DO 10 N = 2, 11
S = S + (-1.0)**N * X**(N/2.0) / FLOAT(N*(N-1))
10 CONTINUE
WRITE (6,20) X, S
20 FORMAT (1X,'X =',F10.4,5X,'S =',F14.6)
STOP
ENDSample run. Input 2 gives
X = 2.0000 S = 0.491971Alternative without powers in the loop (faster): keep a running term. Since , start with T = X (the value of at ) and SG = 1.0, and in each pass use S = S + SG*T/FLOAT(N*(N-1)), then update T = T*SQRT(X) and SG = -SG.
✓ Checked by computer We compiled the program with gfortran and ran it: for X = 2 it prints S = 0.491971, which matches a Python evaluation of the same sum.
What are machine, assembly and high level languages? State their merits and limitations,.
Solution
1. Machine language (first generation). Instructions written in binary (0s and 1s) that the processor executes directly; each instruction has an operation code and memory addresses.
- Merits: executed directly — no translation; fastest execution; full control of the hardware; efficient use of memory.
- Limitations: machine-dependent (a program for one computer does not run on another); very hard to write, read and debug; the programmer must remember codes and manage memory addresses; error-prone and slow to write.
2. Assembly language (second generation). Uses mnemonics (e.g. LOAD, ADD, STORE, JMP) and symbolic names for addresses instead of binary codes; translated into machine language by an assembler, roughly one machine instruction per statement.
- Merits: easier to write and understand than machine language; symbolic addresses; still efficient and close to the hardware; useful for system software, device drivers and time-critical routines.
- Limitations: still machine-dependent; needs knowledge of the hardware; programs are long and tedious; needs an assembler; less productive than high-level languages.
3. High-level languages (third generation and beyond) — FORTRAN, COBOL, BASIC, Pascal, C, and today Python, R, Java. Statements resemble English and mathematical notation (Y = A*X + B); one statement produces many machine instructions; translated by a compiler or interpreter.
- Merits: machine-independent (portable); easy to learn, write, read and maintain; programmer concentrates on the problem, not the machine; built-in library functions and data structures; easier debugging; much higher productivity.
- Limitations: need translation (compile time, compiler software); the object code is usually less efficient in speed and memory than hand-written assembly; less direct control of the hardware.
Summary.
| Machine | Assembly | High-level | |
|---|---|---|---|
| Form | Binary codes | Mnemonics | English-like statements |
| Translator | None | Assembler | Compiler/interpreter |
| Portability | None | None | High |
| Ease of programming | Very hard | Hard | Easy |
| Execution efficiency | Highest | High | Lower |
✓ Answer checked step by step Every point was checked against the standard classification of programming languages.
(i) Distinguish between a FUNCTION sub-programme and a SUBROUTINE sub-programme. Also state the rules governing their use. (ii) Explain the uses of ‘Computed GO TO’ and ‘Assigned GO TO’ statements in FORTRAN. Also state the rules governing their use.
Solution
(i) FUNCTION and SUBROUTINE sub-programmes.
| Point | FUNCTION sub-programme | SUBROUTINE sub-programme |
|---|---|---|
| Purpose | Computes and returns a single value through its name | Performs a task; can return any number of values (or none) through its arguments or COMMON |
| First statement | REAL FUNCTION F(X,Y) or FUNCTION F(X,Y) |
SUBROUTINE S(A,B,N) |
| How called | By using its name in an expression: Z = F(A,B) + 1.0 |
By a CALL statement: CALL S(A,B,N) |
| Name | Has a type (by first letter or type statement) and must be assigned a value inside | Name has no value or type |
| Arguments | At least one argument (in FORTRAN IV) | May have none |
Rules governing their use.
- Each is a separate program unit beginning with
FUNCTION/SUBROUTINEand ending withEND; control returns to the calling program byRETURN. - The actual arguments in the call must agree in number, order and type with the dummy arguments in the definition.
- Dummy arguments can be variables, array names (dimensioned inside), or sub-program names (declared
EXTERNALin the caller). - In a FUNCTION, the function name must be assigned a value before
RETURN. - A sub-programme cannot call itself (no recursion in FORTRAN IV) and must not redefine a constant passed as an argument.
- Variables other than arguments are local; data may also be shared through
COMMONblocks.
Example:
FUNCTION AREA(R)
AREA = 3.14159 * R * R
RETURN
END
SUBROUTINE STATS(X, N, XM, SD)
DIMENSION X(N)
...
RETURN
ENDCalled as A = AREA(2.0) and CALL STATS(X, 50, XM, SD).
(ii) Computed GO TO and Assigned GO TO.
Computed GO TO — a multi-way branch on the value of an integer variable:
GO TO (10, 20, 30), KIf control goes to statement 10, if to 20, if to 30.
- Rules: the index must be an integer variable (an integer expression in FORTRAN 77); the labels must be statement numbers in the same program unit (a label may be repeated); if or the number of labels, control passes to the next statement (in FORTRAN IV the result was undefined); a comma precedes the index.
- Use: choosing among several alternatives, e.g. a menu of options or different formulas by case code.
Assigned GO TO — branch to a label previously stored in an integer variable by an ASSIGN statement:
ASSIGN 50 TO KR
...
GO TO KR, (40, 50, 60)- Rules: the variable must have been given a label by
ASSIGN(not by an ordinary assignmentKR = 50); while it holds a label it must not be used in arithmetic; the list of possible labels (optional in some compilers) must contain the assigned label; all labels must be in the same program unit. - Use: returning from a common block of code to different points (a “local subroutine”), or setting a branch once and using it later.
(Both are obsolete in modern Fortran and are replaced by SELECT CASE and internal procedures.)
✓ Answer checked step by step The FUNCTION/SUBROUTINE example and both GO TO forms were compiled with gfortran (legacy mode) and behaved as described.
Write a FORTRAN programme to calculate the correlation coefficient on the basis of a set of n pairs of observations , , to be read by the programme.
Solution
Formula. For pairs , We compute the means first and then the deviation sums (two passes), which is more accurate than the one-pass “raw sums” formula.
Program.
C CORRELATION COEFFICIENT FROM N PAIRS (X,Y)
DIMENSION X(500), Y(500)
READ (5,*) N
READ (5,*) (X(I), Y(I), I = 1, N)
C MEANS
SX = 0.0
SY = 0.0
DO 10 I = 1, N
SX = SX + X(I)
SY = SY + Y(I)
10 CONTINUE
XB = SX / FLOAT(N)
YB = SY / FLOAT(N)
C SUMS OF SQUARES AND PRODUCTS OF DEVIATIONS
SXX = 0.0
SYY = 0.0
SXY = 0.0
DO 20 I = 1, N
DX = X(I) - XB
DY = Y(I) - YB
SXX = SXX + DX*DX
SYY = SYY + DY*DY
SXY = SXY + DX*DY
20 CONTINUE
R = SXY / SQRT(SXX*SYY)
WRITE (6,30) N, R
30 FORMAT (1X,'N =',I5,5X,'R =',F10.6)
STOP
ENDInput and output. Data are read in free format: first , then the pairs. For the input
5
1 2 2 4 3 5 4 4 5 5the program prints
N = 5 R = 0.774597(Check by hand: , , , , ; .)
Notes. DIMENSION allows up to 500 pairs (enlarge if needed). If all (or all ) are equal, and is undefined; a test IF (SXX*SYY .LE. 0.0) can be added to print a message instead.
✓ Checked by computer We compiled the program with gfortran and ran it on the pairs (1, 2), (2, 4), (3, 5), (4, 4), (5, 5): it prints R = 0.774597, which matches numpy’s corrcoef.
Explain the following control statements in FORTRAN language: (i) Unconditional GO TO (ii) Computed GO TO (iii) Arithmetic IF.
Solution
FORTRAN executes statements in sequence; control statements change this order.
(i) Unconditional GO TO.
GO TO nControl passes always to the statement labelled .
- Example:
GO TO 50jumps to statement 50. - Rules: must be the label of an executable statement in the same program unit. The statement after a GO TO must carry a label, or it can never be reached. It is used to form loops (with an IF to exit) and to skip blocks of statements.
(ii) Computed GO TO.
GO TO (n1, n2, ..., nk), IControl passes to if , to if , …, to if .
- Example:
GO TO (10, 20, 30), MONTH— a three-way branch on the value of MONTH. - Rules: must be an integer variable (FORTRAN IV) with value between 1 and ; otherwise the result is undefined (FORTRAN 77: falls through to the next statement). The labels must be in the same program unit and may repeat. The comma before is required.
(iii) Arithmetic IF.
IF (e) n1, n2, n3The arithmetic expression is evaluated; control passes to if , to if , to if .
- Example: solving a quadratic,
IF (B*B - 4.0*A*C) 10, 20, 30— complex roots at 10, equal roots at 20, distinct real roots at 30. - Rules: may be integer or real (not logical or complex); all three labels must be given (two may be equal, giving a two-way branch); they must be executable statements in the same program unit. Because of rounding, testing a real expression for exactly zero is risky.
(Modern Fortran replaces these with block IF … THEN … ELSE, SELECT CASE and DO WHILE.)
✓ Answer checked step by step Each of the three statements was compiled with gfortran (legacy mode) and branched as described.
Write a FORTRAN program to compute the coefficient of variation from a data set having n ungrouped observations.
Solution
Formula. For ungrouped observations , (If the sample s.d. with divisor is wanted, change FLOAT(N) to FLOAT(N-1) in the s.d. line.)
Program.
C COEFFICIENT OF VARIATION OF N UNGROUPED OBSERVATIONS
DIMENSION X(1000)
READ (5,*) N
READ (5,*) (X(I), I = 1, N)
C MEAN
S1 = 0.0
DO 10 I = 1, N
S1 = S1 + X(I)
10 CONTINUE
XBAR = S1 / FLOAT(N)
C STANDARD DEVIATION
S2 = 0.0
DO 20 I = 1, N
S2 = S2 + (X(I) - XBAR)**2
20 CONTINUE
SD = SQRT(S2 / FLOAT(N))
C COEFFICIENT OF VARIATION (PER CENT)
CV = 100.0 * SD / XBAR
WRITE (6,30) XBAR, SD, CV
30 FORMAT (1X,'MEAN =',F12.4,3X,'S.D. =',F12.4,3X,'C.V. =',F8.2,' %')
STOP
ENDSample run. Input
5
10 12 14 16 18Output:
MEAN = 14.0000 S.D. = 2.8284 C.V. = 20.20 %(Check: , , .)
Note. The C.V. is meaningful only when (ratio-scale data); a check IF (XBAR .LE. 0.0) can print a warning.
✓ Checked by computer We compiled the program with gfortran and ran it on 10, 12, 14, 16, 18: it prints mean 14, s.d. 2.8284 and C.V. 20.20%, matching Python.
More on Optimization Techniques
- All Statistics PYQ solutions, topic by topic
- Optimization Techniques topic-wise PYQs (questions only, for practice)
- Statistics PYQ analysis: which units carry the marks year by year
- Year-wise question papers
- Statistics booklist
Questions: UPSC Civil Services (Main) Examination, Statistics Paper II, 1996–2026. Solutions: Optional Province. Found an error? Tell us.

