0% found this document useful (0 votes)
13 views37 pages

C File

The document discusses generating random samples from various probability distributions in C programming language. It provides code to generate random samples from Poisson, exponential, gamma and standard normal distributions. The code uses functions like fscanf, fprintf and concepts like maximum likelihood estimation, inverse transform sampling and central limit theorem.

Uploaded by

Rashi Pal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views37 pages

C File

The document discusses generating random samples from various probability distributions in C programming language. It provides code to generate random samples from Poisson, exponential, gamma and standard normal distributions. The code uses functions like fscanf, fprintf and concepts like maximum likelihood estimation, inverse transform sampling and central limit theorem.

Uploaded by

Rashi Pal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Programming with C

By-Kashish Arora

Roll number -60

B.sc(hons) Statistics
PRACTICAL 14
AIM: To conduct F-test using f-scanf and f-printf

PROBLEM: Two random samples are drawn from Normal populations and
observations are given. Obtain estimates of the variances of the populations. Then
test whether the populations have equal variances. Note: • Use data in FMS page
16.56 Problem 16.35 • File Read operation required: Input data stored in a file. Use
𝑓𝑠𝑐𝑎𝑛𝑓(…) • File Write operation required: Print your results into another output file.
Use 𝑓𝑝𝑟𝑖𝑛𝑡𝑓(…)

THEORY: fprint and fscanf are functions in C language used for input and output
operations on files.

1. fprintf: It is used to write formatted output to a file. Its syntax is:

- stream: Pointer to the FILE object that identifies the stream where the output is to
be written.
- format: Format control string, similar to the format strings used in `printf`,
containing the text to be written and format specifiers.
Additional arguments corresponding to the format specifiers in the `format` string.

2. fscanf: It is used to read formatted input from a file. Its syntax is:

- stream: Pointer to the FILE object that identifies the stream from which the input
is to be read.
- format: Format control string, similar to the format strings used in `scanf`,
specifying how the input should be interpreted.
Pointers to variables where the values read will be stored, according to the format
specifiers in the `format` string.

Both functions are part of the Standard Input/Output Library (`stdio.h`) in C, and they
operate similarly to their counterparts `printf` and `scanf`, respectively, but with files
instead of the standard input and output streams.

CODE:
// This is Practical 14
#include <stdio.h>

void read_file(char file_name[],int arr[]){


FILE* ptr1 = fopen(file_name, "r");
if ((ptr1 == NULL)) {
printf("no such file.");
}else{
int i = 0;
while (fscanf(ptr1, "%d", &arr[i++]) == 1);
}
fclose(ptr1);
}
float variance(int arr[],int n){
float x_sq= 0,x_sum = 0;
int i;
for(i = 0;i<n;i++){
x_sq += arr[i]*arr[i];
x_sum += arr[i];
}
float fac = (1/((float)n*((float)n-1)));
float x_term = ((n*x_sq)-(x_sum*x_sum));
return(fac*x_term);
}
int main(){
int pop1[10];
int pop2[12];
read_file("pop1.txt",pop1);
read_file("pop2.txt",pop2);

float var1 = variance(pop1,10);


float var2 = variance(pop2,12);
float F = var2/var1;
FILE* output = fopen("Output.txt","w");
fprintf(output,"F(11,9) test statistics is %.2f",F);
fclose(output);
return(0);
}

/*
OUTPUT FOR PRACTICAL 14:
^Z
F(11,9) test statistics is 2.14
*/
PRACTICAL 13
AIM: To develop a function in C to fit a Poisson distribution to the given data
(𝑥𝑖,𝑓𝑖)(xi,fi) for 𝑖=1,2,…,𝑛i=1,2,…,n, where 𝑥𝑖xi represents the observed values and
𝑓𝑖fi represents the frequencies.

PROBLEM: Develop a function to fit a Poisson distribution to the given data {(𝑥𝑖 , 𝑓𝑖
)|𝑖 = 1,2, … , 𝑛}. Hence, demonstrate its use in the 𝑚𝑎𝑖𝑛( ) for given data.
X 0 1 2 3 4 5 6 7 8 Total
f 56 156 132 92 37 22 4 0 1 500

THEORY:
The Poisson distribution is a discrete probability distribution that expresses the
probability of a given number of events occurring in a fixed interval of time or space,
𝑒^(−𝜆)⋅𝜆^𝑘
given the average rate of occurrence. It is given by the formula: P(X=k)= 𝑘!

where λ is the average rate of occurrence and 𝑘k is the number of events.


Fitting Poisson Distribution: To fit a Poisson distribution to data, we need to
estimate the parameter 𝜆λ. The maximum likelihood estimator for λ is given
by: 𝜆^=∑𝑖=1𝑛𝑥𝑖𝑓𝑖∑𝑖=1𝑛𝑓𝑖λ^=∑i=1nfi∑i=1nxifi

CODE:
// This is Practical 13
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define E 2.71828182846

void print_arr(float *x,int n){


int i;
for(i = 0; i<n;i++){
printf("%3.0f ",x[i]);}
printf("\n");
}
float sum_arr(float *x,int n){
int sum=0,i;
for(i =0; i< n;i++){
sum+=x[i];}
return(sum);
}
float mean(float *x,float *f,int n){
float sum=0;
int feq_sum=0;
int i;
for(i =0; i< n;i++){
sum+=(x[i]*f[i]);
feq_sum+=f[i];}
return(sum/(float)feq_sum);
}
float poission(int x,float p,float *ptr,int sum_f){
if(x == 0){
float res = pow(E,(-p));
ptr[x]= res*sum_f;
return (float)res;}else{
float val = (p/x);
float res = val*poission(x-1,p,ptr,sum_f);
ptr[x]= res*sum_f;
return res;}
}
float fit(float *x,float *f,int n){
int sum_f = sum_arr(f,n);
float p = mean(x,f,n);
float *ptr;
ptr = (float*) malloc(n * sizeof(float));
poission(x[n-1],p,ptr,sum_f);
printf("Fitted Poission(%.3f) Data is: \n",p);
printf("X: ");
print_arr(x,n);
printf("F: ");
print_arr(ptr,n);
}
int main() {
float x[] = {0,1,2,3,4,5,6,7,8};
float f[] = {56,156,132,92,37,22,4,0,1};
int n = 9;
fit(x,f,n);
return 0;
}

/* OUTPUT FOR PRACTICAL 13:


Fitted Poission(1.972) Data is:
X: 0 1 2 3 4 5 6 7 8
F: 70 137 135 89 44 17 6 2 0

*/
PRACTICAL 15
Aim:
The aim of this program is to develop a function in C to draw a random sample of
one observation from the Exponential distribution expo(θ). Additionally, the program
will draw a sample of size 10 for the parameter values θ = 0.5 and θ = 1.5.

PROBLEM:

Develop a function to draw a random sample of ONE observation from the


Exponential distribution expo(θ). Hence draw a sample of size 𝑛 = 10 for the
parameter values 𝜃 = 0.5, 1.5

Theory:
The Exponential distribution with parameter θ has a probability density function
(PDF) given by:

𝑓(𝑥∣𝜃)={1𝜃𝑒−𝑥𝜃for 𝑥≥0,0for 𝑥<0.f(x∣θ)={θ1e−θx0for x≥0,for x<0.

To draw a random sample from an Exponential distribution with parameter θ, we can


use the inverse transform method. The cumulative distribution function (CDF) of the
Exponential distribution is:

𝐹(𝑥∣𝜃)=1−𝑒−𝑥𝜃F(x∣θ)=1−e−θx

To generate a random sample from this distribution, we first generate a uniform


random variable 𝑈 on [0, 1] using the rand() function in C. Then, we use the inverse
of the CDF to transform 𝑈 into a sample from the Exponential distribution:

𝑋=−𝜃ln⁡(1−𝑈)X=−θln(1−U)

This transformation ensures that 𝑋X follows the Exponential distribution with


parameter θ.

Code & Output:


// This is Practical 15
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

void print_arr(float *x,int n){


int i;
for(i = 0; i<n;i++){
printf("%3.4f ",x[i]);
}
printf("\n");
}
float get_exp(float lm){
float ran = (float)rand()/RAND_MAX;
float exp = (float)(-1/lm)*(float)log(1-ran);
return exp;
}
void random_sample(float *x,int n,float lm){
int i;
for(i = 0;i <n;i++){
x[i] = (float)get_exp(lm);
}
}
int main() {
srand(401);
float sample[10];
float lm = 0.5;
int n = 10;
random_sample(sample,n,lm);
print_arr(sample,n);

lm = 1.5;
random_sample(sample,n,lm);
print_arr(sample,n);

return 0;
}

/*
OUTPUT FOR PRACTICAL 15:
^Z
0.4161 0.2538 3.6231 3.6234 0.0337 1.4703 0.5423 2.9429 6.8872 4.9648
0.9412 1.4264 0.3218 0.1618 0.5937 0.9685 0.9931 0.3635 0.3894 0.2825
*/
PRACTICAL 16
AIM: To fit a gamma distribution sample.

PROBLEM: Develop a function to draw one random sample from the Gamma
distribution with parameters 𝑆ℎ𝑎𝑝𝑒 = 𝛼 (𝑖𝑛𝑡𝑒𝑔𝑒𝑟) and 𝑆𝑐𝑎𝑙𝑒 = 𝜆 (𝑝𝑜𝑠𝑖𝑡𝑖𝑣𝑒 𝑟𝑒𝑎𝑙).
Hence draw a sample of size 𝑛 = 10 for the parameter values 𝛼 = 3,𝜆 = 1.5.

THEORY: We use RAND_MAX function for this problem.


In C++, `RAND_MAX` is a constant defined in the `<cstdlib>` header file. It
represents the maximum value that can be returned by the `rand()` function, which is
part of the C standard library and used for generating pseudo-random numbers.

CODE:

// This is Practical 16
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

void print_arr(float *x,int n){


int i;
for(i = 0; i<n;i++){
printf("%3.4f ",x[i]);
}
printf("\n");
}
float get_exp(float lm){
float ran = (float)rand()/RAND_MAX;
float exp = (float)(-1/lm)*(float)log(1-ran);
return exp;
}
float get_gamma(int a,float lm){
float value = 0;
int i;
for(i =0 ; i<a;i++){
value += get_exp(lm);
}
return(value);
}
void random_sample(float *x,int n,float lm,int a){
int i;
for(i = 0;i <n;i++){
x[i] = (float)get_gamma(a,lm);
}
}
int main() {
srand(401);
float sample[10];
float lm=1.5;
int n = 10,a = 3;

random_sample(sample,n,lm,a);
print_arr(sample,n);

return 0;
}

/*
OUTPUT FOR PRACTICAL 16:
^Z
1.4310 1.7091 3.4575 4.0226 1.0773 2.3251 1.0792 3.3976 1.7030 0.9984
*/
PRACTICAL 17
AIM: The aim of this program is to develop a function in C to draw one random
sample from the Standard Normal distribution 𝑁(0,1) using the Central Limit
Theorem (CLT).

PROBLEM:
Develop a function to draw one random sample from the Normal distribution 𝑁(0,1)
by using the central limit theorem (CLT). Hence draw a sample of size 𝑛 = 10

THEORY: The Central Limit Theorem states that the sum of a large number of
independent and identically distributed random variables, suitably normalized, will be
approximately normally distributed. We can exploit this theorem to generate a
sample from a normal distribution with mean 0 and standard deviation 1, which is
also called the Standard Normal distribution.

To generate a random sample from 𝑁(0,1) using the CLT, we can take the average
of a large number of uniform random variables and then standardize them.
Specifically, if 𝑈1,𝑈2,…,𝑈𝑛U1,U2,…,Un are independent and identically distributed
uniform random variables on [0, 1], then 𝑍=1𝑛∑𝑖=1𝑛(𝑈𝑖−0.5)Z=n1∑i=1n(Ui−0.5) will
have a distribution that converges to 𝑁(0,1) as 𝑛n approaches infinity.

Code & Output:


#include <stdio.h>
#include <math.h>
#include <stdlib.h>

void print_arr(float *x,int n){


int i;
for(i = 0; i<n;i++){
printf("%3.4f ",x[i]);
}
printf("\n");
}
float get_norm(){
float ran,sum = 0;
int i;
for(i=0;i<75;i++){
ran = (float)rand()/RAND_MAX;
sum += ran;
}
float mn = sum/75;
float norm = (mn-0.5)*(sqrt(12*75));
return(norm);
}
void random_sample(float *x,int n){
int i;
for(i = 0;i <n;i++){
x[i] = get_norm();
}
}
int main() {
srand(556);
int n = 10;
float x[10];
random_sample(x,n);
print_arr(x,n);
return 0;
}

/*
OUTPUT FOR PRACTICAL 17:
^Z
0.0753 -0.8045 -0.7129 -0.7103 0.2700 0.5111 -1.7773 1.9762 -0.5153
0.2053
*/
PRACTICAL 6
AIM: To fit a binomial distribution using recursive function.

PROBLEM: Write a program to generate Binomial distribution probabilities using the


recursive expression 𝑏(𝑥 + 1;𝑛,𝑝) = 𝑛−𝑥 𝑥+1 𝑝 𝑞 𝑏(𝑥;𝑛,𝑝), 𝑥 = 0,1,2,3,…,𝑛 − 1 with
b(0;𝑛,𝑝) = 𝑞𝑛. Test your program using 𝑛 = 5 and 𝑝 = 0.25,0.5,0.75

THEORY: Recursive functions are often used to solve problems that can be broken
down into smaller, similar subproblems.

1. Base Case: Every recursive function must have a base case, which is a condition
under which the function stops calling itself recursively. Without a base case, the
recursion would continue indefinitely, leading to a stack overflow.

2. Recursive Case: In addition to the base case, recursive functions also have a
recursive case, where the function calls itself with modified arguments to solve a
smaller version of the same problem. This process continues until the base case is
reached.

3. Termination: Recursive functions terminate when the base case is met, at which
point the function stops calling itself and returns a value. Each recursive call returns
control to the previous call once the base case is reached.

Recursive functions can be elegant and concise solutions for certain problems, but
they require careful consideration of the base case and the recursive case to ensure
termination and correctness. Additionally, excessive recursion can lead to stack
overflow errors, so it's essential to use recursion judiciously.

CODE:

// This is Practical 6
#include <stdio.h>
#include <math.h>
float binom(int x, int n, float p){
if(x == 0){
float res = pow((1-p),n);
printf("For X = %d, p = %.2f The probability is %f\n",x,p,res);
return (float)res;}else{
float val = (((n-x+1)*p)/(x*(1-p)));
float res = val*binom(x-1,n,p);
printf("For X = %d, p = %.2f The probability is %f\n",x,p,res);
return res;}
}

int main(){
int n = 5;
int x = n;
binom(x,n,0.25);
binom(x,n,0.5);
binom(x,n,0.75);

return 0;
}

/*
OUTPUT FOR PRACTICAL 6:
For X = 0, p = 0.25 The probability is 0.237305
For X = 1, p = 0.25 The probability is 0.395508
For X = 2, p = 0.25 The probability is 0.263672
For X = 3, p = 0.25 The probability is 0.087891
For X = 4, p = 0.25 The probability is 0.014648
For X = 5, p = 0.25 The probability is 0.000977
For X = 0, p = 0.50 The probability is 0.031250
For X = 1, p = 0.50 The probability is 0.156250
For X = 2, p = 0.50 The probability is 0.312500
For X = 3, p = 0.50 The probability is 0.312500
For X = 4, p = 0.50 The probability is 0.156250
For X = 5, p = 0.50 The probability is 0.031250
For X = 0, p = 0.75 The probability is 0.000977
For X = 1, p = 0.75 The probability is 0.014648
For X = 2, p = 0.75 The probability is 0.087891
For X = 3, p = 0.75 The probability is 0.263672
For X = 4, p = 0.75 The probability is 0.395508
For X = 5, p = 0.75 The probability is 0.237305
*/
PRACTICAL 7
AIM: To write a program in C that generates Poisson distribution probabilities using
the recursive expression

PROBLEM: Write a program to generate Poisson distribution probabilities using the


recursive expression 𝑝(𝑥 + 1; 𝜆) = 𝜆/𝑥+1 𝑝(𝑥; 𝜆), 𝑥 = 0,1,2, … with 𝑝(0; 𝜆) = 𝑒 −𝜆 .
Test your program using 𝜆 = 0.01, 0.1, 10.0

Note: (a) The following recursive form is more convenient to write the code: 𝑝(𝑥; 𝜆) =
𝜆 𝑥 𝑝(𝑥 − 1; 𝜆), 𝑥 = 1,2,3, … and 𝑝(0; 𝜆) = 𝑒 −𝜆 .

(b) Develop an appropriate recursive function in C

(c) Terminate computing the next value of 𝑝(𝑥) using the accuracy |1 − ∑ 𝑝(𝑘) 𝑥 𝑘=0
| < 10−4 = 0.0001

THEORY: The Poisson distribution represents the probability of a given number of


events occurring in a fixed interval of time or space, given the average rate of
occurrence, denoted by 𝜆λ.

The recursive formula for the Poisson distribution is given by:


𝑝(𝑥;𝜆)=𝜆𝑥𝑥!𝑒−𝜆p(x;λ)=x!λxe−λ

The task is to compute 𝑝(𝑥) using the recursive form 𝑝(𝑥;𝜆)=𝜆𝑥𝑝(𝑥−1;𝜆)p(x;λ)=xλ


p(x−1;λ) and terminate when the accuracy condition ∣1−∑𝑘=0𝑥𝑝(𝑘)∣<10−4∣1−∑k=0x
p(k)∣<10−4 is met.

CODE:

#include <stdio.h>
#include <math.h>
#define E 2.71828
float poisson(int x,float lm)
{
float res;
static float sum_total =0;
if(x==0)
{
float res0;
res0 = pow(E,(-lm));
sum_total += res0;
printf("For x = %d, p(x;lm = %.2f) = %f\n",x,lm,res0);
return(res0);
}
res = (lm/(float)x)*poisson(x-1,lm);
sum_total+= res;

if((1-sum_total) < 0.0001){


return(0);
}else{
printf("For x = %d, p(x;lm = %.2f) = %f\n",x,lm,res);
return(res);
}
}
int main()
{
poisson(100,0.1);
return(0);
}

/*
OUTPUT FOR PRACTICAL 7:
For x = 0, p(x;lm = 0.10) = 0.904837
For x = 1, p(x;lm = 0.10) = 0.090484
For x = 2, p(x;lm = 0.10) = 0.004524
*/
PRACTICAL 8

AIM:
The aim of the program is to generate Poisson distribution probabilities using a
recursive expression, specifically the formula 𝑝(𝑥 + 1; 𝜆) = 𝜆 / (𝑥 + 1) * 𝑝(𝑥; 𝜆), 𝑥 =
0,1,2, … with 𝑝(0; 𝜆) = 𝑒^−𝜆. The program should test this calculation for different
values of 𝜆, such as 0.01, 0.1, and 10.0.

PROBLEM:
Write a program to generate Poisson distribution probabilities using the recursive
expression 𝑝(𝑥 + 1; 𝜆) = 𝜆 𝑥+1 𝑝(𝑥; 𝜆), 𝑥 = 0,1,2, … with 𝑝(0; 𝜆) = 𝑒 −𝜆 . Test your
program using 𝜆 = 0.01, 0.1, 10.0 Note: (a) The following recursive form is more
convenient to write the code: 𝑝(𝑥; 𝜆) = 𝜆 𝑥 𝑝(𝑥 − 1; 𝜆), 𝑥 = 1,2,3, … and 𝑝(0; 𝜆) = 𝑒 −𝜆
. (b) Develop a function in a separate file and use the static global feature available
in C. (c) Terminate computing the next value of 𝑝(𝑥) using the accuracy |1 − ∑ 𝑝(𝑘) 𝑥
𝑘=0 | < 10−4 = 0.0001

THEORY:
The Poisson distribution is often used to model the number of events occurring in a
fixed interval of time or space. It is characterized by a single parameter 𝜆 (lambda),
which represents the average rate of occurrence of the events. The probability mass
function of the Poisson distribution is given by 𝑝(𝑥; 𝜆) = (𝜆^𝑥 * 𝑒^−𝜆) / 𝑥!, where 𝑥 is
the number of events that occur and 𝑥! is the factorial of 𝑥.

In this program, we will use a recursive expression to calculate the Poisson


distribution probabilities. The recursive formula 𝑝(𝑥; 𝜆) = 𝜆 / 𝑥 * 𝑝(𝑥 − 1; 𝜆), 𝑥 = 1,2,3,
… and 𝑝(0; 𝜆) = 𝑒^−𝜆 can be used to calculate the probabilities. We will use a static
global variable to store the value of 𝑝(𝑥) as we calculate it recursively. We will
terminate the calculation when the accuracy of the sum of probabilities |1 − ∑ 𝑝(𝑘)
𝑘=0^𝑥 | < 10^−4 = 0.0001.
In C, the static keyword is used to declare variables with static storage duration,
which means that the variable retains its value between function calls and exists
throughout the lifetime of the program. When the static keyword is used at the global
scope (outside of any function), it creates a global variable that is local to the file in
which it is declared.

CODE:
// This is Practical 8
#include <stdio.h>

// Declaration of functions in other files.


float init(float lm);
float poission_value(int x, float lm);

float poisson(int x,float lm){


float res;
if(x==0)
{
return(init(lm));
}
return (poission_value(x,lm));
}

int main()
{
poisson(100,0.01);
printf("\n");
poisson(100,0.1);
printf("\n");
poisson(100,10.0);
printf("\n");
return(0);
}

//file2
#include <stdio.h>
#include <math.h>
#define E 2.71828

static float sum_total;


float poisson(int x,float lm);

float init(float lm){


float res;
res = pow(E,(-lm));
sum_total = res;
printf("For x = 0, p(x;lm = %2.2f) = %.5f\n",lm,res);
return (float)res;
}
int check(){
if((1-sum_total) < 1e-4){return 0;
}else{return 1;}
}

float poission_value(int x, float lm){


float res;
if(x==0){return(init(lm));}
res = (lm/(float)x)*poisson(x-1,lm);
sum_total+= res;
if(check()){
printf("For x = %2d, p(x;lm = %2.2f) = %.5f\n",x,lm,res);
return(res);
}else{return(0);}
}

/* OUTPUT FOR PRACTICAL 8:


For x = 0, p(x;lm = 0.01) = 0.99005
For x = 0, p(x;lm = 0.10) = 0.90484
For x = 1, p(x;lm = 0.10) = 0.09048
For x = 2, p(x;lm = 0.10) = 0.00452

For x = 0, p(x;lm = 10.00) = 0.00005


For x = 1, p(x;lm = 10.00) = 0.00045
For x = 2, p(x;lm = 10.00) = 0.00227
For x = 3, p(x;lm = 10.00) = 0.00757
For x = 4, p(x;lm = 10.00) = 0.01892
For x = 5, p(x;lm = 10.00) = 0.03783
For x = 6, p(x;lm = 10.00) = 0.06306
For x = 7, p(x;lm = 10.00) = 0.09008
For x = 8, p(x;lm = 10.00) = 0.11260
For x = 9, p(x;lm = 10.00) = 0.12511
For x = 10, p(x;lm = 10.00) = 0.12511
For x = 11, p(x;lm = 10.00) = 0.11374
For x = 12, p(x;lm = 10.00) = 0.09478
For x = 13, p(x;lm = 10.00) = 0.07291
For x = 14, p(x;lm = 10.00) = 0.05208
For x = 15, p(x;lm = 10.00) = 0.03472
For x = 16, p(x;lm = 10.00) = 0.02170
For x = 17, p(x;lm = 10.00) = 0.01276
For x = 18, p(x;lm = 10.00) = 0.00709
For x = 19, p(x;lm = 10.00) = 0.00373
For x = 20, p(x;lm = 10.00) = 0.00187
For x = 21, p(x;lm = 10.00) = 0.00089
For x = 22, p(x;lm = 10.00) = 0.00040
For x = 23, p(x;lm = 10.00) = 0.00018
*/
PRACTICAL 9

AIM: To develop a function sort(int *x, int n) that reorders an array of integers into
ascending order using the Bubble sort algorithm

PROBLEM: Develop a function 𝑠𝑜𝑟𝑡(𝑖𝑛𝑡 ∗ 𝑥, 𝑖𝑛𝑡 𝑛) to reorder an array of integers into


the ascending order using Bubble sort algorithm. Hence, demonstrate its use in the
𝑚𝑎𝑖𝑛( ) function to sort an array of random numbers 𝑋~𝑈[0,50] (integers). Display
the sorted sequence of numbers alone with numbers in the intermediate steps after
each swap operation. What is the total number of swaps? Hint: • Develop a function
𝑠𝑤𝑎𝑝(𝑖𝑛𝑡 ∗ 𝑎, 𝑖𝑛𝑡 ∗ 𝑏) and use it in the 𝑠𝑜𝑟𝑡 function. • To generate a sequence of 8
numbers, use 𝑥𝑖 = 𝑟𝑎𝑛𝑑𝑜𝑚(51)

THEORY: The program will demonstrate the use of this function in the main()
function to sort an array of random numbers 𝑋∼𝑈[0,50]X∼U[0,50] (integers). It will
display the sorted sequence of numbers along with the numbers in the intermediate
steps after each swap operation. The program will also calculate and display the
total number of swaps. The Bubble sort algorithm is a simple sorting algorithm that
repeatedly steps through the list, compares adjacent elements, and swaps them if
they are in the wrong order. The pass through the list is repeated until the list is
sorted.

CODE:

#include <stdio.h>
#include <stdlib.h>

int swaps_no;
int random2(int x)
{
float i = (rand()/(float)RAND_MAX);
return (i*x);
}
void gen_rand(int *x,int n,int k){
int i;
for(i = 0; i <n; i++){
x[i] = random2(k+1);
}
}
void print_arr(int *x,int n){
int i;
for(i = 0; i<n;i++){
printf("%d ",x[i]);
}
printf("\n");
}
void swap(int *a, int *b){
int temp;
temp = *b;
*b = *a;
*a = temp;
swaps_no++;
}
void sort(int *x,int n){
int i,j;
for(i=0;i<n-1;i++){
for(j = 0; j <n-1-i;j++){
if( (x[j]) > (x[j+1])){
swap(&x[j],&x[j+1]);
print_arr(x,n);
}
}
}
}
int main(){
int n=8;
int k = 51;
int x[8];
int i;
for(i = 0; i <n; i++){
x[i] = random2(k+1);
}
sort(x,n);
print_arr(x,n);
printf("\nNo of swaps are: %d\n",swaps_no);

return(0);
}

/*
OUTPUT FOR PRACTICAL 9:
^Z
20 43 40 41 47 10 17 39
20 40 43 41 47 10 17 39
20 40 41 43 47 10 17 39
20 40 41 43 10 47 17 39
20 40 41 43 10 17 47 39
20 40 41 43 10 17 39 47
20 40 41 10 43 17 39 47
20 40 41 10 17 43 39 47
20 40 41 10 17 39 43 47
20 40 10 41 17 39 43 47
20 40 10 17 41 39 43 47
20 40 10 17 39 41 43 47
20 10 40 17 39 41 43 47
20 10 17 40 39 41 43 47
20 10 17 39 40 41 43 47
10 20 17 39 40 41 43 47
10 17 20 39 40 41 43 47
10 17 20 39 40 41 43 47

No of swaps are: 17
*/
Practical 10
AIM: Develop a function to calculate Mean and hence another function to calculate
Variance of Raw data {𝑥𝑖 for 𝑖 = 1,2, … 𝑛}. Test these by calling from a 𝑚𝑎𝑖𝑛( )
function with real data type.

Note: Use 𝑥𝑖 = 110 + 5 ∗ (𝑟𝑎𝑛𝑑( )/(𝑅𝐴𝑁𝐷_𝑀𝐴𝑋 + 1.0)) to generate data.

Theory:

• Mean is given by, μ=E[X]=∑xi⋅P(X=xi)


• Variance is given by, σ2=Var[X]=∑(xi−μ)2⋅P(X=xi)

Code & Output:


#include <stdio.h>
#include <stdlib.h>

void print_arr(float *x,int n){


int i;
for(i = 0; i<n;i++){
printf("%f ",x[i]);
}
printf("\n");
}

float mean(float *x, int n)


{
float sum=0;
int i;
for(i =0; i< n;i++){
sum+=x[i];
}
return(sum/(float)n);
}

float sum_sq(float *x, int n)


{
float sum=0;
int i;
for(i =0; i< n;i++){
sum+=(x[i]*x[i]);
}
return(sum/(float)n);
}

float variance(float *x, int n){


float mn = mean(x,n);
float sum_s = sum_sq(x,n);
return(sum_s-(mn*mn));
}

int main(){
int n = 5;
float x[5];
int i;
for(i = 0; i <n; i++){
x[i] = 110+ (5*rand())/(RAND_MAX+1.0);
}
print_arr(x,n);
printf("Mean of the data is %f\n",mean(x,n));
printf("Variance of the data is %f\n",variance(x,n));
return(0);
}

/* OUTPUT FOR PRACTICAL 10:


110.200935 109.971916 109.915497 109.992203 110.558235
Mean of the data is 110.127762
Variance of the data is 0.053711
*/
PRACTICAL 11
AIM:

To develop a function in C to calculate the mean and another function to calculate


the variance of grouped frequency data (𝑥𝑖,𝑓𝑖)(xi,fi) for 𝑖=1,2,…,𝑛i=1,2,…,n.

PROBLEM: Develop a function to calculate Mean and hence another function to calculate
Variance of grouped frequency data {(𝑥𝑖 , 𝑓𝑖 ) for 𝑖 = 1,2, … 𝑛}. Test these by calling from a
𝑚𝑎𝑖𝑛( ) function with 𝑓𝑙𝑜𝑎𝑡 data type.

X 10.5 15.5 20.5 25.5 30.5 35.5 40.5 45.5

f 7 6 19 35 30 23 7 1

THEORY:

Mean (Average): The mean of grouped frequency data is calculated using the
formula: Mean=∑𝑖=1𝑛𝑥𝑖𝑓𝑖∑𝑖=1𝑛𝑓𝑖 where 𝑥𝑖xi is the midpoint of the ith class
interval and 𝑓𝑖fi is the frequency of the ith class interval.
Variance: The variance of grouped frequency data is calculated using the
𝑓𝑖⋅(𝑥𝑖−𝑥ˉ)2
formula: σ2= ∑𝑖 where 𝑥𝑖 is the midpoint of the ith class interval, 𝑓𝑖 is
𝑁
the frequency of the ith class interval, and Mean is the mean calculated earlier.

CODE:

// This is Practical 11
#include <stdio.h>
#include <stdlib.h>

void print_arr(float *x,int n){


int i;
for(i = 0; i<n;i++){
printf("%.1f ",x[i]);
}
printf("\n");
}
float mean(float *x,float *f,int n){
float sum=0;
int feq_sum=0;
int i;
for(i =0; i< n;i++){
sum+=(x[i]*f[i]);
feq_sum+=f[i];
}
return(sum/(float)feq_sum);
}
float sum_sq(float *x, float *f ,int n){
float sum=0;
int feq_sum=0;
int i;
for(i =0; i< n;i++){
sum+=(x[i]*x[i]*f[i]);
feq_sum+=f[i];
}
return(sum/(float)feq_sum);
}
float variance(float *x,float *f,int n){
float mn = mean(x,f,n);
float sum_s = sum_sq(x,f,n);
return(sum_s-(mn*mn));
}

int main() {
int n = 8;
float x[8]={10.5,15.5,20.5,25.5,30.5,35.5,40.5,45.5};
float f[8]= {7,6,19,35,30,23,7,1};
print_arr(x,n);
print_arr(f,n);
printf("Mean of the data is %f\n",mean(x,f,n));
printf("Variance of the data is %f\n",variance(x,f,n));
return 0;
}

/*
OUTPUT FOR PRACTICAL 11:
10.5 15.5 20.5 25.5 30.5 35.5 40.5 45.5
7.0 6.0 19.0 35.0 30.0 23.0 7.0 1.0
Mean of the data is 27.414062
Variance of the data is 56.297302
*/
PRACTICAL 12
AIM: Fit Binomial Distribution for grouped data.

PROBLEM:
Develop a function to fit a Binomial distribution to the given data {(𝑥𝑖,𝑓𝑖)|𝑖 = 1,2, …,𝑛}.
Hence, demonstrate its use in the 𝑚𝑎𝑖𝑛( ) for given data. (see FMS Example 8.19)

X 0 1 2 3 4 5 6 7 Total
f 7 6 19 35 30 23 7 1 128

THEORY: A binomial distribution describes the number of successes in a fixed


number of independent Bernoulli trials, where each trial has two possible outcomes:
success or failure. The distribution is characterized by two parameters: the number
of trials (n) and the probability of success in each trial ((p)).

Binomial Distribution is given by,

P(X=k)=𝐶𝑘𝑛 pk(1−p)n−k

CODE:
// This is Practical 12
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void print_arr(float *x,int n){


int i;
for(i = 0; i<n;i++){
printf("%3.0f ",x[i]);
}
printf("\n");
}
float sum_arr(float *x,int n){
int sum=0,i;
for(i =0; i< n;i++){
sum+=x[i];
}
return(sum);
}
float mean(float *x,float *f,int n){
float sum=0;
int feq_sum=0;
int i;
for(i =0; i< n;i++){
sum+=(x[i]*f[i]);
feq_sum+=f[i];
}
return(sum/(float)feq_sum);
}
float sum_sq(float *x, float *f ,int n){
float sum=0;
int feq_sum=0;
int i;
for(i =0; i< n;i++){
sum+=(x[i]*x[i]*f[i]);
feq_sum+=f[i];
}
return(sum/(float)feq_sum);
}
float variance(float *x,float *f,int n){
float mn = mean(x,f,n);
float sum_s = sum_sq(x,f,n);
return(sum_s-(mn*mn));
}
float binom(int x, int n, float p,float *ptr,int sum_f){
if(x == 0){
float res = pow((1-p),n);
ptr[x]= res*sum_f;
return (float)res;}else{
float val = (((n-x+1)*p)/(x*(1-p)));
float res = val*binom(x-1,n,p,ptr,sum_f);
ptr[x]= res*sum_f;
return res;}
}
float fit(float *x,float *f,int n){
int sum_f = sum_arr(f,n);
float mn = mean(x,f,n);
float vr = variance(x,f,n);
float p = 1-(vr/mn);
int n2 = mn/p;
float *ptr;
ptr = (float*) malloc(n * sizeof(float));
binom(x[n-1],n2,p,ptr,sum_f);
printf("Fitted Data is: \n");
printf("X: ");
print_arr(x,n);
printf("F: ");
print_arr(ptr,n);
}
int main() {
float x[] = {0,1,2,3,4,5,6,7};
float f[] = {7,6,19,35,30,23,7,1};
int n = 8;
fit(x,f,n);
return 0;
}

/*
OUTPUT FOR PRACTICAL 12:
^Z
Fitted Data is:
X: 0 1 2 3 4 5 6 7
F: 2 11 25 33 29 18 7 2

*/
PRACTICAL 18
AIM: To carry out matrix operations in C.

PROBLEM: Develop functions to carryout the following Matrix operations:


• Input (read matrix), Output (write matrix),
• Addition,
• Subtraction
• Multiplication
• Transpose
Test your program with suitable examples.

THEORY: Matrix operations in C++ involve performing mathematical operations on


matrices, such as addition, subtraction, multiplication, and inversion. Here's a brief
overview:

1. Matrix Representation:
- Matrices are typically represented using 2D arrays in C++.
- Each element of the array corresponds to an element of the matrix.

2. Matrix Addition and Subtraction:


- Matrix addition and subtraction are performed element-wise.
- Two matrices can be added or subtracted if they have the same dimensions
(same number of rows and columns).

3. Matrix Multiplication:
- Matrix multiplication is a bit more involved than addition and subtraction.
- The product of two matrices ( A ) and ( B ), denoted as ( AB ), is calculated by
taking the dot product of rows of ( A ) with columns of ( B ).
- The number of columns in the first matrix must equal the number of rows in the
second matrix.
- The resulting matrix has the number of rows of the first matrix and the number of
columns of the second matrix.

4. Matrix Inversion:
- Matrix inversion is the process of finding the inverse of a matrix.
- The inverse of a matrix ( A ), denoted as ( A^{-1} ), is such that ( A times A^{-1} =
A^{-1} times A = I ), where ( I ) is the identity matrix.
- Not all matrices have inverses; square matrices with non-zero determinants have
inverses.

5. Library Support:
- C++ provides libraries like the Standard Template Library (STL) and external
libraries like Eigen or Armadillo for matrix operations.
- These libraries offer efficient implementations of various matrix operations and
often include additional functionalities like matrix decomposition, solving linear
equations, and more.
CODE:
// This is Practical 18
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define R1 3
#define C1 3
#define R2 3
#define C2 3
void read_matrix(int row, int col,int arr[row][col]){
int i,j;
for(i =0;i<row;i++){
for(j=0;j<col;j++){
scanf("%d",&arr[i][j]);
}
}
}
void print_matrix(int row, int col,int arr[row][col]){
int i,j;
for(i =0;i<row;i++){
for(j=0;j<col;j++){
printf("%3d ",arr[i][j]);
}
printf("\n");
}
}
void mat_addition(int rows, int cols,int A[rows][cols],int
B[rows][cols],int R[rows][cols]){
int i,j;
for(i =0;i<rows;i++){
for(j=0;j<cols;j++){
R[i][j] = A[i][j]+B[i][j];
}
}
}
void mat_subtraction(int rows, int cols,int A[rows][cols],int
B[rows][cols],int R[rows][cols]){
int i,j;
for(i =0;i<rows;i++){
for(j=0;j<cols;j++){
R[i][j] = A[i][j]- B[i][j];
}
}
}
void mat_mult(int r1, int c1,int r2, int c2,int A[r1][c1],int
B[r2][c2],int R[r1][c2]){
if(c1!= r2){printf("Matrix multiplication not possible");return;}
int i,j,k;
int sum;
for(i =0;i<r1;i++){
for(j=0;j<c2;j++){
sum = 0;
for(k=0;k<c1;k++){
sum += A[i][k]*B[k][j] ;
}
R[i][j] = sum;
}
}
}
void transpose(int row,int col,int y[row][col]){
int i,j,tmp;
for(i=0;i<row;i++)
for(j=0;j<i;j++)
{
tmp = y[i][j];
y[i][j] = y[j][i];
y[j][i] = tmp;
}
}
int main(){
int M1[R1][C1];
int M2[R2][C2];
int res[R1][C1];
printf("Enter Values of Matrix 1: \n");
read_matrix(R1,C1,M1);
printf("Enter Values of Matrix 2: \n");
read_matrix(R2,C2,M2);
printf("Matrix 1 is :\n");
print_matrix(R1,C1,M1);
printf("Matrix 2 is :\n");
print_matrix(R2,C2,M2);

printf("Matrix Addition :\n");


mat_addition(R1,C1,M1,M2,res);
print_matrix(R1,C1,res);
printf("Matrix Subtraction :\n");
mat_subtraction(R1,C1,M1,M2,res);
print_matrix(R1,C1,res);
printf("Matrix Multiplication :\n");
mat_mult(R1,C1,R2,C2,M1,M2,res);
print_matrix(R1,C2,res);
printf("Matrix Transpose :\n");
transpose(R1,C2,M1);
print_matrix(R1,C1,M1);
return 0;
}
/*
OUTPUT FOR PRACTICAL 18:
^Z
Enter Values of Matrix 1:
1 2 3 4 5 6 7 8 9
Enter Values of Matrix 2:
1 2 3 4 5 6 7 8 9
Matrix 1 is :
1 2 3
4 5 6
7 8 9
Matrix 2 is :
1 2 3
4 5 6
7 8 9
Matrix Addition :
2 4 6
8 10 12
14 16 18
Matrix Subtraction :
0 0 0
0 0 0
0 0 0
Matrix Multiplication :
30 36 42
66 81 96
102 126 150
Matrix Transpose :
1 4 7
2 5 8
3 6 9
*/
PRACTICAL 1
AIM: To understand the behavior of the getchar() function in C when comparing its
return value to EOF

PROBLEM: Write a program to verify that the expression getchar()!= EOF is 0 or 1.


THEORY:
• getchar(): This function in C is used to read a single character from the
standard input stream (stdin). It returns the character read as an unsigned
char cast to an int or EOF (defined in <stdio.h>) to indicate an end-of-file
condition or an error.
• EOF: This is a constant defined in <stdio.h> that represents the end-of-file
condition.

CODE:

//This is Practical 1
#include <stdio.h>

int main() {
int i = getchar()!= EOF;
printf("%d",i);
return 0;
}

/* OUTPUT FOR PRACTICAL 1:


0
*/
PRACTICAL 2

AIM: To count the number of characters using getchar()!= EOF.

PROBLEM: Write a program to count the number of characters on the input using
getchar()!=EOF

THEORY:

1. getchar(): This is a standard C function declared in `<stdio.h>`. It reads a single


character from the standard input (stdin) and returns it as an `int`. If there are no
more characters to read, it returns `EOF`.

2. EOF (End of File): EOF is a macro defined in `<stdio.h>`. It's a signal indicating
that there are no more characters to read from the input stream. It's typically
represented by the integer value `-1`.

3. Using != EOF: The expression `(getchar() != EOF)` is a conditional expression. It


reads a character using `getchar()` and compares it to `EOF`. If the character read is
not equal to EOF, the condition evaluates to true, and the loop continues. If the
character read is EOF, indicating the end of input, the condition evaluates to false,
and the loop terminates.

4. Counting Characters: By using `(getchar() != EOF)` as the loop condition, the


program can count characters from input until the end of file is reached. Each time
the loop iterates, it reads a character and increments the character count.

CODE:

// This is Practical 2
#include <stdio.h>

int main() {
int len=0;
while(getchar()!=EOF){
len++;
}
printf("length is %d",len);
return 0;
}
/*
OUTPUT FOR PRACTICAL 2:
abcd
length is 5
*/

Practical 3
AIM: Write a program to count blanks, tabs and new-lines on the input. (Hint: either
use scanf("%[-]s", var) feature of scanf(...) or use getchar() !=EOF to store a string
on input to be terminated with EOF).
Theory:

• The getchar() function does not require any arguments. It simply reads a
single character from the input stream and returns it as an integer value. If
successful, it returns the character read as an unsigned char cast to an int or
EOF (end-of-file) if there is no more input available.
• The scanf() function takes a format string as its first argument, which
specifies the format of the input to be read. The subsequent arguments are
pointers to variables where the input values will be stored.
Code & Output:
// This is Practical 3
#include <stdio.h>

int main() {
int line = 0;
int tab = 0;
int blank = 0;
int i;
do
{
i = getchar();
if(i == '\n'){
line++;
}else if (i == ' ')
{
blank++;
}else if(i == '\t'){
tab++;}
} while (i != EOF);
printf("The Number of \nlines : %d\nTabs : %d\nBlanks :
%d\n",line,tab,blank);
return 0;
}

/* OUTPUT FOR PRACTICAL 3:


The Number of
lines : 2
Tabs : 1
Blanks : 1
*/
PRACTICAL 4:

AIM: to implement the trimup() function in C programming. This function will take a
string as input and modify it

PROBLEM: Develop a function trimup() such that when a string is passed into it the
characters, except in the range A-Zor a-z, are removed and the lower case
characters are converted to upper case.

THEORY: he function will iterate over each character in the input string. For each
character, it will check if it falls within the desired range (A-Z or a-z). If it does, the
character will be preserved or converted to uppercase if it is a lowercase letter. If the
character does not fall within the desired range, it will be removed from the output
string.

CODE:
// This is Practical 4
#include <stdio.h>

void trimup(char *a,int len){


printf("%s\n",a);
char b[len];
int cor = 0;
for(int i=0; i <= len;i++){
if(a[i]<91 && a[i]>64){
b[cor] = a[i];
cor++;
}else if (a[i]<123 && a[i]>96)
{
b[cor] = a[i]-32;
cor++;
}else{
continue;}
}
b[cor] = '\0';
printf("%s",b);
}

int main(){
char a[]="A4__r*787ya%$n";
int len=14;
trimup(a,len);
return 0;
}
/*
OUTPUT FOR PRACTICAL 4:
A4__r*787ya%$n
ARYAN
*/
PRACTICAL 5:

AIM: To demonstrate the behavior of integer overflow in C by sequentially adding or


subtracting 1 to a variable starting from a value near the maximum positive or
negative limit of an int data type.

PROBLEM: It is known that the range of numbers for int data type is -32768 to
+32767. Using integer variables verify the numbers, which results on adding +1 (or
subtracting-1) sequentially in starting from, say, +32760 (or-32760). Hence confirm
the 2's complement representation for integral numbers in C.

THEORY: For a 16-bit integer (int), the range of numbers is from -32768 to +32767.
When you add 1 to +32767, it overflows and wraps around to -32768. Similarly,
when you subtract 1 from -32768, it overflows and wraps around to +32767.

By observing this behavior, we can confirm that C uses two's complement


representation for integers, where overflow results in wrapping around the maximum
positive or negative value.

CODE:
// This is Practical 5
#include <stdio.h>

int main() {
int i;
int n = 32763;
for(i=1;i<7;i++){
printf("%d\n",n+i);
}
return 0;
}

/*
OUTPUT FOR PRACTICAL 5:
32764
32765
32766
32767
-32768
-32767
*/

You might also like