Knowledge is the key to immortality
SOME PROGRAMS IN C - PART 7
Prepared by Ratul Chakraborty - Associate Professor - Statistics

Some programs in C - Part 7

 

1) Simple Random Sampling With Replacement (SRSWR)

The Program

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

unsigned int myrand(unsigned int);

int main()
{
	unsigned int N, n, count = 0, rand_number;
	
	printf("INSERT POPULATION SIZE & SAMPLE SIZE : ");
	scanf("%u%u",&N,&n);
	
	srand(time(0));
	
	printf("\n%u RANDOM SAMPLES BY SRSWR\n\n",n);
	while(count < n){
		rand_number = myrand(N);
		printf("%u\t",rand_number);
		count++;
	}	

	return 0;
}

unsigned int myrand(unsigned int popusize){
	unsigned int randvalue;
		
	randvalue = (rand() + 1) % popusize;
	return (randvalue == 0)? popusize : randvalue;
}

Output

INSERT POPULATION SIZE & SAMPLE SIZE : 20 10

10 RANDOM SAMPLES BY SRSWR

10      15      6       13      9       9       18      14      15      14

 

2) Simple Random Sampling Without Replacement (SRSWOR)

The Program

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

#define MAX 1000

unsigned int myrand(unsigned int);

int main()
{
	unsigned int N, n, samples[MAX], i, randobs, found, count = 0;
	
	printf("INSERT POPULATION SIZE & SAMPLE SIZE : ");
	scanf("%u%u",&N,&n);
	
	if(n > N){
		printf("\nSAMPLE SIZE CANN'T BE LARGER THAN POPULATION SIZE");
		return 0;
	}
	
	if(n > MAX){
		printf("\nMAXIMUM SAMPLE SIZE IS %u", MAX);
		return 0;
	}

	srand(time(0));
	
	printf("\n%u RANDOM SAMPLES BY SRSWOR\n\n",n);
	while(count < n){
		found = 0;
		randobs = myrand(N);
		for(i=0; i<count; i++){
			if(samples[i] == randobs){
				found = 1;
				break;
			}
		}
		
		if(found == 0){
			samples[i] = randobs;	
			count++;	
			printf("%u\t",randobs);
		}
	}	

	return 0;
}

unsigned int myrand(unsigned int popusize){
	unsigned int randvalue;
		
	randvalue = (rand() + 1) % popusize;
	return (randvalue == 0)? popusize : randvalue;
}

Output

INSERT POPULATION SIZE & SAMPLE SIZE : 20 10

10 RANDOM SAMPLES BY SRSWOR

6       19      12      20      17      5       11      18      9       3
Copyright © 2018 - All Rights Reserved - www.mbbcollege.in